当前位置: 首页 > news >正文

TCP协议实现一对一聊天

服务端代码:

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 Send extends Thread{
    private Socket socket;
    public Send(Socket socket){
        this.socket  =socket;
    }
    @Override
    public void run() {
        this.sendMsy();
    }
    /**
     * 发送消息
     */
    private void sendMsy(){
        Scanner scanner =null;
        PrintWriter pw =null;
        try{
            scanner =new Scanner(System.in);
            pw =new PrintWriter(this.socket.getOutputStream());
            while(true){
                String str =scanner.nextLine();
                pw.println(str);
                pw.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (scanner!=null){
                scanner.close();
            }
            if (pw!=null){
                pw.close();
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
 
/**
 * 接收消息的线程
 */
class receive extends Thread{
    private Socket socket=null;
    public receive(Socket socket){
        this.socket =socket;
    }
 
    @Override
    public void run() {
        this.receiveMsg();
    }
    /**
     * 用于接收对方消息
     */
    private void receiveMsg(){
        BufferedReader br =null;
        try{
            br =new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            while(true){
                String mr = br.readLine();
                System.out.println("A说:"+mr);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
        }
    }
}
 
public class ChatSocketServer {
    public static void main(String[] args) {
        ServerSocket serverSocket =null;
        try{
            serverSocket =new ServerSocket(8888);
            System.out.println("服务端已启动等待连接");
            Socket socket = serverSocket.accept();
            System.out.println("连接成功!");
            new Send(socket).start();
            new receive(socket).start();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
客户端代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
 
public class ChatSocketClient {
    public static void main(String[] args) {
 
        try {
            Socket socket =new Socket("127.0.0.1",8888);
            System.out.println("连接成功!");
            new ClientSend(socket).start();
            new Clientreive(socket).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/**
 * 用于发送消息线程类
 */
class ClientSend extends Thread{
    @Override
    public void run() {
        this.sendMsy();
    }
    private Socket socket;
    public ClientSend(Socket socket){
        this.socket  =socket;
    }
    /**
     * 发送消息
     */
    private void sendMsy(){
        Scanner scanner =null;
        PrintWriter pw =null;
        try{
            scanner =new Scanner(System.in);
            pw =new PrintWriter(this.socket.getOutputStream());
            while(true){
                String str =scanner.nextLine();
                pw.println(str);
                pw.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (scanner!=null){
                scanner.close();
            }
            if (pw!=null){
                pw.close();
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
 
/**
 *用于接收消息线程类
 */
class Clientreive extends Thread{
    private Socket socket=null;
    public Clientreive(Socket socket){
        this.socket =socket;
    }
 
    @Override
    public void run() {
        this.receiveMsg();
    }
    /**
     * 用于接收对方消息
     */
    private void receiveMsg(){
        BufferedReader br =null;
        try{
            br =new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            while(true){
                String mr = br.readLine();
                System.out.println("B说:"+mr);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
        }
    }
}
运行服务端代码后,再运行客户端代码,即可实现一对一聊天。

http://www.lryc.cn/news/255431.html

相关文章:

  • python使用conda管理多个环境
  • 实现个微机器人的二次开发
  • Android 记录一些Framework开发的命令
  • Ant Design Vue 年选择器
  • AGM CPLD 应用指南
  • (1)词法分析器
  • 丢掉破解版,官方免费了!!!
  • Termux
  • yolo目标检测+目标跟踪+车辆计数+车辆分割+车道线变更检测+速度估计
  • 基于Java酒店管理系统
  • GoLong的学习之路,进阶,微服务之原理,RPC
  • vLLM介绍
  • DevOps搭建(一)-之swappiness安装详细步骤
  • 微软发布Orca2,“调教式”教会小规模大语言模型如何推理!
  • JVM 内存回收算法
  • 11.28~11.29基本二叉树的性质、定义、复习;排序算法;堆
  • 轮播插件Slick.js使用方法详解
  • postgresql pg_hba.conf 配置详解
  • 使用粗糙贴图制作粗纹皮革手提包3D模型
  • Chrome清除特定网站的Cookie,从而让网址能正常运行(例如GPT)
  • history路由解决刷新出现404的问题
  • ubuntu22下使用nvidia 2080T显卡部署pytorch
  • 【Spark基础】-- 理解 Spark shuffle
  • 软件测试入门:静态测试
  • 力扣labuladong一刷day30天二叉树
  • 【云原生-K8s】检查yaml文件安全配置kubesec部署及使用
  • LeetCode力扣每日一题(Java):20、有效的括号
  • 解决Flutter运行报错Could not run build/ios/iphoneos/Runner.app
  • 配置Smart Link主备备份示例
  • 03-微服务架构构建之微服务拆分