学无先后,达者为师

网站首页 编程语言 正文

TCP通信的实现-优化点对点聊天

作者:Qiddo 更新时间: 2023-12-12 编程语言

在上一篇博客中聊天的功能已经实现,但为了更为方便发送和接收信息,将代码合并(客户端和服务端一起处理),全部代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 发送消息线程
 */
class Send1 extends Thread{
    private Socket socket;
    private Scanner scanner;
    public Send1(Socket socket,Scanner scanner){
        this.socket = socket;
        this.scanner = scanner;
    }
    @Override
    public void run() {
        this.sendMsg();
    }
    /**
     * 发送消息
     */
    private void sendMsg(){

        //创建向对方输出消息的流对象
        try(PrintWriter pw = new PrintWriter(this.socket.getOutputStream())){

            while(true){
                String msg = scanner.nextLine();
                pw.println(msg);
                pw.flush();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

/**
 * 接收消息的线程
 */
class Receive1 extends Thread{
    private Socket socket;
    public Receive1(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        this.receiveMsg();
    }
    /**
     * 用于接收对方消息的方法
     */
    private void receiveMsg(){
        //创建用于接收对方发送消息的流对象
        try(BufferedReader br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()))){

            while(true){
                String msg = br.readLine();
                System.out.println("他说:"+msg);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

public class GoodTCP {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        try{
            //实例化键盘输入
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入:server,<port>或者:<ip>,<port>");
            String str = scanner.nextLine();
            String[] arr = str.split(",");
            if("server".equals(arr[0])){
                //启动服务端
                System.out.println("TCP Server Listen at "+arr[1]+".......");
                serverSocket = new ServerSocket(Integer.parseInt(arr[1]));
                socket = serverSocket.accept();
            }else{
                //启动客户端
                socket = new Socket(arr[0],Integer.parseInt(arr[1]));
                System.out.println("连接成功!");
            }
            //启动发送消息的线程
            new Send1(socket,scanner).start();
            //启动接收消息的线程
            new Receive1(socket).start();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

代码需运行两次,一次作为客户端,一次作为服务端,实现点对点的聊天功能。

原文链接:https://blog.csdn.net/m0_73944607/article/details/130893883

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新