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

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.lryc.cn/news/259025.html

相关文章:

  • 全面高压化与全面超快充,破解新能源汽车的时代难题
  • 02 CSS基础入门
  • MyBatis框架中的5种设计模式总结
  • ffmpeg相关命令
  • 锂电3V升12V1A升压芯片WT3209
  • Unity 置顶OpenFileDialog文件选择框
  • oomall课堂笔记
  • Qt6.5类库实例大全:QFrame
  • Java 数据结构篇-用数组、堆实现优先级队列
  • Reactor模型
  • 【SpringCloud】通过Redis手动更新Ribbon缓存来解决Eureka微服务架构中服务下线感知的问题
  • 如何做好性能压测?压测环境设计和搭建的7个步骤你知道吗?
  • Qt12.13
  • 目标检测YOLO系列从入门到精通技术详解100篇-【目标检测】SLAM(基础篇)(五)
  • 鸿蒙开发之页面与组件生命周期
  • Kotlin开发之低功耗蓝牙(引用三方库)的详解一
  • 5G/4G工业DTU扬尘在线监测:解决工地扬尘困扰的最佳方案
  • 思源黑体某些字显示成日式中文,太先进了(附解法)
  • .NET医院检验系统LIS源码,使用了oracle数据库,保证数据的隔离和安全性
  • html实现动漫视频网站模板源码
  • python zblog API实现类似XMLRPC/发布文章
  • 后台业务管理系统原型模板,Axure后台组件库(整套后台管理页面)
  • kyuubi整合flink yarn application model
  • 使用openpyxl调整Excel的宽度
  • 前端面试——CSS面经(持续更新)
  • 【C语言】结构体实现位段
  • IEEE RAS 机器人最优控制(Model-based Optimization for Robotics)学习资料
  • redis中缓存雪崩,缓存穿透,缓存击穿等
  • C_8练习题答案
  • Web漏洞分析-文件解析及上传(中)