欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java socket-3--多客户端与服务器的交互

程序员文章站 2024-03-23 09:40:52
...

上一篇> java socket-2–即时通信

利用多线程,每当一个客户端发送一个请求过来,就使用一个子线程去处理它
不过此代码只可以做到多客户端向服务端发送信息,不能做到服务端对多客户端发送信息
客户端的代码与上篇的客户端代码一样,所以不贴出来,只贴服务端的代码


服务端

package 通信1;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerThreadDemo {

    public static void main(String[] args){
    Socket client = null;
    ServerSocket server = null;

    try {

        server = new ServerSocket(10007);

    } catch (IOException e1) {
        e1.printStackTrace();
    }

    int num = 1;

    while(true){
        try {
        client = server.accept();
        System.out.println("客户端"+num+"已经连接");
        new Thread(new ThreadServer(num, client)).start();
        num++;
        } catch (IOException e) {
        e.printStackTrace();
        }

    }

    }

}  


class ThreadServer implements Runnable{
    private String name;
    private int num;
    private Socket client;

    public ThreadServer(int num,Socket client){
    this.num = num;
    this.client = client;
    }


    public void run(){

    new Thread(new ServerReadThread1(client,num)).start();
    new Thread(new ServerWriteThread1(client)).start();
    }


}

//--------------------------------------------------------处理读操作的线程
class ServerReadThread1 implements Runnable{

  private Socket client = null;
  private int num ;
  public ServerReadThread1(Socket client,int num){
    this.num = num;
    this.client = client;

  }

  public void run(){

    //--------------------------------------------------接受来自客户端的信息
    DataInputStream dis = null;  
    try {
        while(true){
            dis = new DataInputStream(client.getInputStream()); //读取客户端的信息              
            String inMess = dis.readUTF();
            System.out.println("客户端"+num+"说:"+inMess); 
        }    
        } catch (IOException e) {

        System.out.println("失去连接");
        // e.printStackTrace();
       }            

  }

}

//----------------------------------------------------------处理写的线程

class ServerWriteThread1 implements Runnable{
  private Socket client = null;
  public ServerWriteThread1(Socket client){
    this.client = client;
  }

  public void run(){
    BufferedReader in = null;
    DataOutputStream dos = null;  

    try {
        while(true){
            dos = new DataOutputStream(client.getOutputStream()); 
            //-----------------------------------------------从键盘获得消息
            in = new BufferedReader(new InputStreamReader(System.in));
            String mess  = in.readLine();
            dos.writeUTF(mess);
            System.out.println("服务端:"+mess);
        }
        } catch (IOException e) {
        //失去连接
        e.printStackTrace();
        }
  }

}

上一篇: 相交链表160

下一篇: Ajax 入门