天天看點

java socket 實作服務端與用戶端------一對多的服務端和客戶機

http://www.51testing.com/html/48/202848-122580.html

//一對多的服務端和客戶機:一個服務端能同時服務多個用戶端,需要使用多線程來實作

//服務端:調用具體的處理線程完成處理

package com.socket.multiserver;

import java.io.*;

import java.net.*;

import com.socket.multiserver.ChildTh;

public class MyMultiServer {

 public static void main(String[] args) throws IOException{

  ServerSocket server=new ServerSocket(5678);

  while (true){

                Socket client=server.accept();

                ChildTh child=new ChildTh(client);//用socket執行個體初始化具體的處理線程對象

                //使用Runnable接口和使用extends Thread的差別:

                // 如果是使用Runnable接口,需要這麼寫:

                   new Thread(child).start();               

                //注意:不能寫成:child.run();

                // 如果使用extends Thread,隻需要child.start()就可以,因為start()是Thread的方法

                }

        }

}      

============================================================

//處理線程類:

package com.socket.multiserver;

import java.io.*;

import java.net.*;

public class ChildTh implements Runnable{

        private Socket client;

        public ChildTh(Socket client){

                this.client=client;

        }

        public void run(){       

           try{       

             BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));

             PrintWriter ut=new PrintWriter(client.getOutputStream());

             while(true){

                     String str=in.readLine();

                     System.out.println(str);

                     out.println("has receive....");

                     out.flush();

                     if(str.equals("end"))

                        break;

             }       

             client.close();

            }catch(Exception e){

                  System.out.println("error in the close the socket!");                       

                  e.printStackTrace();

              }

              finally{

              }

        }

===========================================================

//用戶端

package com.socket.multiserver;

import java.net.*;

import java.io.*;

public class MyMultiClient{

 static Socket client;

 public static void main(String[] args)throws Exception{

  client=new Socket(InetAddress.getLocalHost(),5678);

         BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));

         PrintWriter ut=new PrintWriter(client.getOutputStream());

         //從标準輸入接收資料

  BufferedReader wt=new BufferedReader(new InputStreamReader(System.in));

  while(true){

           String str=wt.readLine();

           //String str = "jonathan";

           out.println(str);

           out.flush();

           if(str.equals("end")){

                    break;

          }

           System.out.println(in.readLine());

  }

  client.close();

 }

}

繼續閱讀