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

TCP实现一对一聊天

一,创建类

二,类

1.ChatSocketServer类
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();
                }
            }
        }
    }
}

2.ChatSocketClient类
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.kler.cn/news/160293.html

相关文章:

  • 介绍 Apache Spark 的基本概念和在大数据分析中的应用。
  • 大数据-之LibrA数据库系统告警处理(ALM-37014 Gaussdb进程锁文件已经存在)
  • Web前端JS如何获取 Video/Audio 视音频声道(左右声道|多声道)、视音频轨道、音频流数据
  • 力扣每日一题:2646. 最小化旅行的价格总和(2023-12-06)
  • HarmonyOS4.0从零开始的开发教程05 应用程序入口—UIAbility的使用
  • C++EasyX之井字棋
  • 【华为数据之道学习笔记】3-1 基于数据特性的分类管理框架
  • 大数据可视化项目——基于Python豆瓣电影数据可视化分析系统的设计与实现
  • AIGC: 关于ChatGPT中基于Whisper模型实现音频转文本
  • Java利用UDP实现简单群聊
  • 做题笔记:SQL Sever 方式做牛客SQL的题目--VQ35
  • Java开源工具库Guava使用指南详解
  • sqlite3.44.2的编译
  • centos7安装rabbitMQ
  • Jenkins UI 自动化持续化集成测试
  • linux缓冲区(buff/cache)内存占用过高解决办法
  • 从零开发短视频电商 Jmeter压测示例模板详解(无认证场景)
  • 2023年山东省职业院校技能大赛信息安全管理与评估第一阶段样题
  • ffmpeg与opencv-python处理视频
  • 聚观早报 |东方甄选将上架文旅产品;IBM首台模块化量子计算机
  • 准确!!!在 CentOS 8 上配置 PostgreSQL 14 的主从复制
  • 2024年江苏省职业院校技能大赛信息安全管理与评估 第三阶段学生组(样卷)
  • Qt进程和线程
  • B 站基于 StarRocks 构建大数据元仓
  • 后端返回数据前端保留两位小数
  • 8-tornado中模板的使用(通过字符串返回、通过模板Template返回、通过模板render返回)、模板案例
  • Elasticsearch,Kibana集成,x-pack鉴权配置
  • Pandas 打开有密码的Excel
  • Python中函数添加超时时间,Python中signal使用
  • Linux中的输入输出重定向