多线程java socket编程示例 -凯发k8网页登录

posts - 310, comments - 6939, trackbacks - 0, articles - 3
  凯发k8网页登录-凯发天生赢家一触即发官网 :: 凯发k8网页登录首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

多线程java socket编程示例

posted on 2007-10-15 12:37 诗特林 阅读(92331) 评论(25)     所属分类: socket
                                                 多线程java socket编程示例

这篇做为学习孙卫琴<>的学习笔记吧.其中采用java 5的executorservice来进行线程池的方式实现多线程,模拟客户端多用户向同一服务器端发送请求.

1.服务端
package sterning;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.io.printwriter;
import java.net.*;
import java.util.concurrent.*;

public class multithreadserver {
    
private int port=8821;
    
private serversocket serversocket;
    
private executorservice executorservice;//线程池
    private final int pool_size=10;//单个cpu线程池大小
    
    
public multithreadserver() throws ioexception{
        serversocket
=new serversocket(port);
        
//runtime的availableprocessor()方法返回当前系统的cpu数目.
        executorservice=executors.newfixedthreadpool(runtime.getruntime().availableprocessors()*pool_size);
        system.out.println(
"服务器启动");
    }

    
    
public void service(){
        
while(true){
            socket socket
=null;
            
try {
                
//接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
                socket=serversocket.accept();
                executorservice.execute(
new handler(socket));
                
            }
 catch (exception e) {
                e.printstacktrace();
            }

        }

    }

    
    
public static void main(string[] args) throws ioexception {
        
new multithreadserver().service();
    }


}


class handler implements runnable{
    
private socket socket;
    
public handler(socket socket){
        
this.socket=socket;
    }

    
private printwriter getwriter(socket socket) throws ioexception{
        outputstream socketout
=socket.getoutputstream();
        
return new printwriter(socketout,true);
    }

    
private bufferedreader getreader(socket socket) throws ioexception{
        inputstream socketin
=socket.getinputstream();
        
return new bufferedreader(new inputstreamreader(socketin));
    }

    
public string echo(string msg){
        
return "echo:"msg;
    }

    
public void run(){
        
try {
            system.out.println(
"new connection accepted "socket.getinetaddress()":"socket.getport());
            bufferedreader br
=getreader(socket);
            printwriter pw
=getwriter(socket);
            string msg
=null;
            
while((msg=br.readline())!=null){
                system.out.println(msg);
                pw.println(echo(msg));
                
if(msg.equals("bye"))
                    
break;
            }

        }
 catch (ioexception e) {
            e.printstacktrace();
        }
finally{
            
try {
                
if(socket!=null)
                    socket.close();
            }
 catch (ioexception e) {
                e.printstacktrace();
            }

        }

    }

}

2.客户端
package sterning;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.socket;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;

public class multithreadclient {
    
    
public static void main(string[] args) {
        
int numtasks = 10;
        
        executorservice exec 
= executors.newcachedthreadpool();

        
for (int i = 0; i < numtasks; i{
            exec.execute(createtask(i));
        }


    }


    
// 定义一个简单的任务
    private static runnable createtask(final int taskid) {
        
return new runnable() {
            
private socket socket = null;
            
private int port=8821;

            
public void run() {
                system.out.println(
"task "  taskid  ":start");
                
try {                    
                    socket 
= new socket("localhost", port);
                    
// 发送关闭命令
                    outputstream socketout = socket.getoutputstream();
                    socketout.write(
"shutdown\r\n".getbytes());

                    
// 接收服务器的反馈
                    bufferedreader br = new bufferedreader(
                            
new inputstreamreader(socket.getinputstream()));
                    string msg 
= null;
                    
while ((msg = br.readline()) != null)
                        system.out.println(msg);
                }
 catch (ioexception e) {                    
                    e.printstacktrace();
                }

            }


        }
;
    }

}


从而实现了多个客户端向服务器端发送请求,服务器端采用多线程的方式来处理的情况.再结合我之前的例子---java基于socket文件传输示例,就可以实现多线程文件的传输了

评论

# re: 多线程java socket编程示例  回复     

2007-11-10 14:25 by
请问作者:
可不可以利用服务端主动发信?

# re: 多线程java socket编程示例  回复     

2007-12-07 13:12 by
膏药帖~~

# re: 多线程java socket编程示例  回复     

2008-01-07 22:19 by
很好!不错!

# re: 多线程java socket编程示例  回复     

2008-03-14 11:36 by
dgdfggfdgdf

# re: 多线程java socket编程示例  回复     

2008-05-28 17:14 by
我也是参照孙的书,可是运行不能得到正确的结果!很是郁闷啊
[code]
package com.zz.socket;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.printwriter;
import java.net.serversocket;
import java.net.socket;

public class echoserver {

private int port = 8000;
private serversocket ss;

public echoserver() throws ioexception {
ss = new serversocket(port);
system.out.println("server is starting....");
}

private string echostring(string msg){
return "echo:" msg;
}
public static void main(string[] args) {
try {
new echoserver().service();
} catch (ioexception e) {
e.printstacktrace();
}
}

private void service(){
while(true){
socket s = null;
try{
s = ss.accept();
system.out.println("a client is coming......");
bufferedreader br = this.getreader(s);
printwriter pw = this.getwriter(s);
string msg = null;
while((msg = br.readline()) != null){
system.out.println(msg);
pw.println(this.echostring(msg) "\n");
pw.flush();
if(msg.equals("bye")) break;
}
}catch(ioexception e ){

}
}
}

private printwriter getwriter(socket s) throws ioexception {
return new printwriter(s.getoutputstream());
}

private bufferedreader getreader(socket s) throws ioexception {
return new bufferedreader(new inputstreamreader(s.getinputstream()));
}

}



[/code]

# re: 多线程java socket编程示例  回复     

2008-05-28 17:15 by
package com.zz.socket;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.printwriter;
import java.net.socket;

public class echoclient {
private string host = "localhost";
private int port = 8000;
private socket socket;

private echoclient() throws ioexception {
socket = new socket(host, port);
}

public void talk() throws ioexception {
try {
bufferedreader br = getreader(socket);
printwriter pw = getwriter(socket);
bufferedreader localreader = new bufferedreader(
new inputstreamreader(system.in));
string msg = null;
while ((msg = localreader.readline())!= null) {
pw.println(msg "\n");
pw.flush();
system.out.println(br.readline());
if (msg.equals("bye"))
break;
}
} catch (ioexception e) {
} finally {
try {
socket.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}

private printwriter getwriter(socket s) throws ioexception {
return new printwriter(s.getoutputstream());
}

private bufferedreader getreader(socket s) throws ioexception {
return new bufferedreader(new inputstreamreader(s.getinputstream()));
}

/**
* @param args
* @throws ioexception
*/
public static void main(string[] args) throws ioexception {
new echoclient().talk();

}

}

# re: 多线程java socket编程示例  回复     

2008-06-16 23:04 by 有猫相伴的日子
这个代码有很多问题,如请求处理,怎么封装请求对象,把请求对象放一队列

从服务器端怎么发消息到客户端.....

# re: 多线程java socket编程示例  回复     

2009-04-27 10:22 by
貌似整体思想可以,但是,程序的问题就比较多了...

# re: 多线程java socket编程示例[未登录]  回复     

2009-05-07 15:38 by
第三方杀毒

# re: 多线程java socket编程示例  回复     

2009-05-07 17:14 by
如果多个线程对同一资源进行读取,能保证资源的原子性吗?应该对资源加锁

# re: 多线程java socket编程示例  回复     

2009-05-17 15:52 by
正找这样的文章 多谢

# re: 多线程java socket编程示例[未登录]  回复     

2009-08-23 19:12 by
如何设定超时的问题呢?

# re: 多线程java socket编程示例  回复     

2010-05-09 13:48 by
我是java网络编程的初学者很想加 诗特林 为好友向你请教些问题。我的qq826463574

# re: 多线程java socket编程示例  回复     

2010-05-09 14:05 by
服务器端:
public class multithreadserver {
private int port=8821;
private serversocket serversocket;
private executorservice executorservice;//线程池
private final int pool_size=10;//单个cpu线程池大小

public multithreadserver() throws ioexception{
serversocket=new serversocket(port);
//runtime的availableprocessor()方法返回当前系统的cpu数目.
executorservice=executors.newfixedthreadpool(runtime.getruntime().availableprocessors()*pool_size);
system.out.println("服务器启动");
}

public void service(){
while(true){
socket socket=null;
try {
//接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
socket=serversocket.accept();
executorservice.execute(new handler(socket));

} catch (exception e) {
e.printstacktrace();
}
}
}

public static void main(string[] args) throws ioexception {
new multithreadserver().service();
}

}

class handler implements runnable{
private socket socket;
public handler(socket socket){
this.socket=socket;
}
/*private dataoutputstream dos(socket socket) throws ioexception{
outputstream socketout=socket.getoutputstream();
return new dataoutputstream(socketout);
}
private datainputstream dis(socket socket) throws ioexception{
inputstream socketin=socket.getinputstream();
return new datainputstream(socketin);
}*/

public void run(){
try {
system.out.println("new connection accepted " socket.getinetaddress() ":" socket.getport());
outputstream os = socket.getoutputstream();
dataoutputstream dos = new dataoutputstream(os);

inputstream is = socket.getinputstream( );
datainputstream dis=new datainputstream(is);
new myserverread(dis).start();
new myserverwite(dos).start();


} catch (ioexception e) {
e.printstacktrace();
}/*finally{
try {
if(socket!=null)
socket.close();
} catch (ioexception e) {
e.printstacktrace();
}
}*/
}
}
class myserverread extends thread{
private datainputstream dis;
public myserverread (datainputstream dis){
this.dis=dis;
}
public void run(){
string info;
try{
while(true)
{
info=dis.readutf();
system.out.println("对方说" info);
if (info.equals("bye")){
system.out.println("对方下线,程序退出");
system.exit(0);}
}
}
catch (exception e){e.getstacktrace();}

}
}

class myserverwite extends thread{
private dataoutputstream dos;
public myserverwite (dataoutputstream dos){
this.dos=dos;
}
public void run(){
bufferedreader br=new bufferedreader(new inputstreamreader(system.in));
string info;
try{
while(true)
{
info=br.readline();
dos.writeutf(info);
if (info.equals("bye")){
system.out.println("自己下线,程序退出");
system.exit(0);}
}
}
catch (exception e){e.getstacktrace();}

}
}



# re: 多线程java socket编程示例  回复     

2010-05-09 14:06 by
客户端:


import java.io.bufferedreader;
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.socket;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;



public class multithreadclient {

public static void main(string[] args) {
int id=info.i;

executorservice exec = executors.newcachedthreadpool();

/* for (int i = 0; i < numtasks; i ) {
exec.execute(createtask(i));
}
*/
system.out.println("客户端线程" id "已启动~~");
exec.execute(createtask(id));
info.i=id ;

}

// 定义一个简单的任务
private static runnable createtask(int taskid) {
// this.taskid=taskid;
return new runnable() {
private socket socket = null;
private int port=8821;

public void run() {

// system.out.println("task " taskid ":start");
try {
socket = new socket("localhost", port);
// 发送关闭命令
inputstream is = socket.getinputstream( );
datainputstream dis=new datainputstream(is);

outputstream os = socket.getoutputstream();
dataoutputstream dos = new dataoutputstream(os);

new myclientread(dis).start();
new myclientwite(dos).start();

} catch (ioexception e) {
e.printstacktrace();
}
}

};
}
}
class myclientread extends thread{
private datainputstream dis;
public myclientread (datainputstream dis){
this.dis=dis;
}
public void run(){
string info;
try{
while(true)
{
info=dis.readutf();
system.out.println("对方说" info);
if (info.equals("bye")){
system.out.println("对方下线,程序退出");
system.exit(0);}
}
}
catch (exception e){e.getstacktrace();}

}
}

class myclientwite extends thread{
private dataoutputstream dos;
public myclientwite (dataoutputstream dos){
this.dos=dos;
}
public void run(){
bufferedreader br=new bufferedreader(new inputstreamreader(system.in));
string info;
try{
while(true)
{
info=br.readline();
dos.writeutf(info);
if (info.equals("bye")){
system.out.println("自己下线,程序退出");
system.exit(0);}
}
}
catch (exception e){}

}
}

这个程序我想实现多用户与服务器的连接交互问题,但是能过连接上但是不能实现交互,这是为什么呢?我是java网络编程初学者谢谢您的指教急待您的回复!

# re: 多线程java socket编程示例[未登录]  回复     

2010-08-19 16:52 by
学习了

# re: 多线程java socket编程示例  回复     

2012-04-01 16:54 by
你好,这样不会出现中文乱码吗?

# re: 多线程java socket编程示例[未登录]  回复     

2013-06-03 20:55 by
求 超市收银系统 用xml socket 和多线程 做的 有的发我邮箱 769566815@qq.com

# re: 多线程java socket编程示例[未登录]  回复     

2013-06-03 20:58 by
跪求 急用 6月5号交上去

# re: 多线程java socket编程示例  回复     

2014-04-30 10:37 by
@钟侥
while(true){
socket s = null;

每次s都是null

# re: 多线程java socket编程示例  回复     

2014-04-30 10:42 by
看错了,

s = ss.accept();

你那个代码变量名太差了吧!看都看不清!

# re: 多线程java socket编程示例  回复     

2014-05-22 16:29 by
请问您知不知道哪里有socket的学习视频啊?因为手头资料实在有限,有好多不懂的地方。如果有的话请发到我的邮箱960696649@qq.com,麻烦您了~

# re: 多线程java socket编程示例  回复     

2014-07-30 22:02 by
很不错的socket教程

# re: 多线程java socket编程示例  回复     

2014-11-18 16:42 by
@有猫相伴的日子
项目中正打算使用这段代码的,看你的品论才发现 确实没有用到队列,如果并发数量超过线程数会出现什么情况?

只有注册用户后才能发表评论。


网站导航:
              
 
网站地图