Socket编程(网络编程)-----基于TCP和多线程的聊天室

Socket 编程

两台电脑之间的通讯链路被称为“套接字”(Socket),是提供给应用程序的接口。
Socket编程中的主要相关类:

  • InetAddress类(定义主机:IP、HostName、域名)
  • ServerSocket类(TCP)
  • Socket类(TCP)
  • InputStream
  • OutputStream
  • DatagramSocket(UDP)
  • DatagramPacket(UDP)

ServerSocket类的主要方法

Socket编程(网络编程)-----基于TCP和多线程的聊天室_第1张图片
Socket类的主要方法
Socket编程(网络编程)-----基于TCP和多线程的聊天室_第2张图片
ServerSocket类的主要作用是建立连接 ,提供端口,开启通讯线程。
Socket类的作用与File类类似,提供数据传输的源。

基于TCP的Socket

Socket通信模型:
进行网络通信时,Socket需要借助字节流(outputStream inputStream)来完成数据的传递工作

例子 多人聊天室

服务器代码

	public class TCPService {
    public static HashMap onlineUsers = new HashMap();
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(18888);
            System.out.println("端口开启");
            while(true){
                Socket client = serverSocket.accept();//会有阻塞   有一个新用户 执行一次
                Worker worker = new Worker(client);
                worker.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/**
 * 使用多线程 可以接受多个通话
 */
class Worker extends Thread{
    private  Socket client;

    public Worker (Socket client){
        this.client = client;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = client.getInputStream();
            int lengle = 0;
            byte[] buffer = new byte[1024];
            StringBuffer in = new StringBuffer();
            while ((lengle = inputStream.read(buffer)) > 0) {
                String info = new String(buffer, 0, lengle);
                in.append(info);
                //报文分析
                analysis(info);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void analysis(String info){
        System.out.println("报文分析中"+info);
        String[] data = info.split("-");

        if(data[0].equals("management")){
            if(data[1].equals("login")){
                TCPService.onlineUsers.put(data[2],this.client);
                sendMessage(data[2],"登录成功");
            }else if(data[1].equals("logout")){
                TCPService.onlineUsers.remove(data[2]);
                sendMessage(data[2],"注销完毕");
            }else if(data[1].equals("onlineusers")){
                String names = "";
                for (Map.Entry entry: TCPService.onlineUsers.entrySet()) {
                    names += entry.getKey() + "-";
                    sendMessage(data[2], "message-onlineusers-" + names);
                }
            }
        }else if(data[0].equals("message")){
            int a1 = 0;
            for (Map.Entry entry: TCPService.onlineUsers.entrySet()) {
                if(data[2].equals(entry.getKey())){
                    sendMessage(data[2],data[3]);
                    a1 = 1;
                    break;
                }
            }
            if(a1 == 0){
                String message = "此人没有上线";
                sendMessage(data[1],message);
            }
        }


    }
    public void sendMessage(String name, String info){
        Socket socket = TCPService.onlineUsers.get(name);
        try{
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(info.getBytes());
            outputStream.flush();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

客户端

public class TCPClient {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    try {
        Socket socket = new Socket("127.0.0.1",18888);
        //接收服务器返回的报文信息
        Receive receiver = new Receive(socket);
        receiver.start();

        //输出:接收聊天内容
        OutputStream outputStream = socket.getOutputStream();
        System.out.println("请输入账号登录");
        String loginmanage = new String("management-login-");
        String login =scanner.next();
        loginmanage+=login;
        outputStream.write(loginmanage.getBytes());
        outputStream.flush();

        System.out.println("请输入聊天的人");
        String  who = scanner.next();

        while (true) {
            System.out.println("请输入信息:");
            String info = "message-"+login+"-"+ who+"-"+scanner.next();
            outputStream.write(info.getBytes());
            outputStream.flush();
        }
    }catch (Exception e){

    }
}

}
class Receive extends Thread{
Socket socket;

public Receive(Socket socket) {
    this.socket = socket;
}

@Override
public void run() {

    while(true){
        try{
            InputStream inputStream = this.socket.getInputStream();
            byte[] buffer = new byte[1024];
            int position = inputStream.read(buffer);
            String info = new String(buffer, 0, position);
            System.out.println("客户端:服务器返回的数据:" + info);
        }catch (Exception e){

       	 }
  	  }
	}
}

客户端可以都复制几个一起跑

你可能感兴趣的:(java基础)