栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

 

先放两张运行图

代码很简单,只要一个服务器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("rn"+"服务器连接成功,可以发送消息!");
            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("rn" + "服务器的消息:" + 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();
    }
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/603085.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号