多线程TCP程序服务器端

多线程TCP程序服务器端:

1.创建ServerSocket对象,指定监听的端口号。

2.把accept()方法作为循环条件,循环监听客户端请求。

3.创建线程类,定义一个socket类型的成员变量,并定义一个可以为他赋值的构造函数方法。

4.在run()方法中使用socket变量进行任意的通信操作。

5.在主线程的循环体内开启一个线程,并传入accept()方法的返回值。

比如:

 1 public void main(String [] args){
 2     ServerSocket ss=new ServerSocket(8888);
 3     Socket s=null;
 4     while((s=ss.accept())!=null){
 5         new  MyThread(s).start();
 6     }
 7     ss.close();
 8 }
 9 
10 class MyThread extends Thread{
11     private Socket socket;
12     public MyThread(Socket socket){
13         super();
14         this.socket=socket;
15     }
16     public void run(){
17         try{
18             OutputStream os=socket.getOutputStream();
19             PrintWriter pw=new PrintWrite(os);
20             pw.println("something");
21             pw.flush();
22             pw.close();
23             socket.close();
24         }catch(IOException e){
25         }
26     }
27 }

这里

posted @ 2013-07-01 13:40  一种微笑  Views(433)  Comments(0)    收藏  举报