Java--利用TCP编写一个简单的聊天工具

该博客介绍了一个使用Java实现的简单TCP聊天应用,通过内网穿透技术,使得客户端能与服务器进行实时消息传递。服务器端创建ServerSocket监听9999端口,接收并处理客户端连接。客户端通过Socket连接服务器,发送和接收消息。代码中包含发送端和接收端的实现,实现了双向通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

先放两张运行图

代码很简单,只要一个服务器class和客户端的class即可,我用了内网穿透代替了“127.0.0.1”的ip,所以只要当我服务端开启的时候,客户端无论在哪都可以跟客户端发送消息,具体内网穿透功能这里就不赘述了,各位自行百度吧。接下来就是代码部分

server端

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;


public class server {
    private static DataInputStream dis;
    private static DataOutputStream dos;
    private static int root = 1;

    public static void main(String[] args) {
        new server().startServer();
    }

    public static void startServer() {
        try {
            //服务器在9990端口监听客户端的连接
            ServerSocket ss = new ServerSocket(9999);
            System.out.println("server is listening...");
            Thread t1 = new Thread(new fasong());//发送端
            t1.start();

            while (true) {
                //阻塞的accept方法,当一个客户端连接上,才会返回Socket对象
                Socket s = ss.accept();
                System.out.println("客户端连接成功!");
                dis = new DataInputStream(s.getInputStream());
                dos = new DataOutputStream(s.getOutputStream());
                //开启线程处理通信
                Thread t2 = new Thread(new jieshou());//接收端
                // recevie(s);
                t2.start();

            }

        } catch (IOException e) {
            System.out.println("已断开连接");
           return;
        }
    }

    static class fasong implements Runnable {
        private boolean flag = true;

        @Override
        public synchronized void run() {
          o:  while (true ) {
                Scanner scanner = new Scanner(System.in);
                String line = null;
                while ((line = scanner.nextLine()) != null && line.length() > 0) {
                    try {
                        dos.writeUTF(line);
                        System.out.println("服务端:" + line);
                    } catch (SocketException e) {
                        flag = false;
                    } catch (IOException e) {
                        e.printStackTrace();
                        flag = false;
                    }
                }
            }
        }
    }

    static class jieshou implements Runnable {
        private boolean flag = true;

        @Override
        public synchronized void run() {
          root = 1;
            while (flag) {
                String msg = null;
                try {
                    while ((msg = dis.readUTF()) != null) {
                        System.out.println("客户端发送的消息 :" + msg);
                    }
                } catch (EOFException e) {
                    System.out.println("已断开连接......");
                    flag = false;
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
            System.out.println("接收端结束");
            root = -1;

        }

    }
}

客户端

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        new Client().startClient();
    }

    public void startClient() {
        try {
            //连接到服务器
            System.out.println("连接服务器中.....");
            for (int i = 0; i < 10; i++) {
                System.out.print("--");
                Thread.sleep(200);
            }
            Socket socket = new Socket("127.0.0.1", 9999);
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            System.out.println("\r\n"+"服务器连接成功,可以发送消息!");
            System.out.print("我:");
            Scanner scanner = new Scanner(System.in);
            String line = null;
            listenServerReply(dis);
            while ((line = scanner.nextLine()) != null) {//读取从键盘输入的一行
                if (line.length() > 0)
                    dos.writeUTF(line);//发给服务端
                System.out.print("客户端:");
            }
        } catch (SocketException e) {
            System.out.println("服务器断开,发送失败");
            startClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //监听服务端回复的消息
    public void listenServerReply(final DataInputStream dis) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String line = null;
                try {
                    while ((line = dis.readUTF()) != null && line.length() > 0) {

                        System.out.println("\r\n" + "服务器的消息:" + line);
                        System.out.print("我:");
                    }
                } catch (EOFException e) {
                    System.out.println("服务器已断开连接......5s后自动退出");

                    try {
                        for (int i = 5; i > 0; i--) {
                            System.out.println(i);
                            Thread.sleep(1000);
                        }
                        System.exit(0);

                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值