Java实现简单的聊天工具

先看代码:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Sender {
    private static DatagramSocket send; //套接字
    private static byte[] buff;    //缓冲区
    private static DatagramPacket packetReceived;  //接收的包
    private static InetAddress inetAddress;


    public Sender() throws Exception {
        buff = new byte[1024];
        packetReceived = new DatagramPacket(buff,buff.length);
        inetAddress = InetAddress.getByName("localhost");
        send = new DatagramSocket(5000);
    }

    private static String send() throws IOException {
        Scanner scan = new Scanner(System.in);
        //要发送的信息
        String str = scan.next();
        byte[] buff = str.getBytes();
        //数据报文
        DatagramPacket datagramPacket = new DatagramPacket(buff,buff.length,inetAddress,4000);
        //发送
        send.send(datagramPacket);
        return str;
    }

    private static String receive() throws IOException {
        send.receive(packetReceived);
        String str = new String(packetReceived.getData(),0,packetReceived.getLength());
        return str;
    }

    public static void main(String[] args) throws Exception {
        Sender sender = new Sender();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    String msg = null;
                    try {
                        msg = send();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(msg.equals("bye")){
                        send.close();
                        System.out.println("本次聊天结束");
                        System.exit(0);

                    }
                }
            }
        }.start(); //创建线程,调用start方法启动线程
        new Thread(){
            @Override
            public void run() {
                while (true) {
                    String msg = null;
                    try {
                        msg = receive();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.printf("%s:%s\n",packetReceived.getAddress().getHostAddress(),msg);
                    if(msg.equals("bye")){
                        send.close();
                        System.out.println("本次聊天结束");
                        System.exit(0);
                    }
                }
            }
        }.start();
    }
}

 这实现了一个简单的聊天聊天工具,当然仅平这一个类还是不够的,如果是打算在自己电脑上实现两天,则需要在写一个类,代码跟这个一模一样,改改类名就好,然后运行两个类,就可以互发信息了.如果想在两台电脑之间通信,就需要在另一台电脑上也写上代码,然后将inetAddress = InetAddress.getByName("localhost");里面的localhost改成对方的ip地址,注意两台电脑须在同意局域网下,方可通信

你可能感兴趣的:(java)