TCP和UDP实现聊天

TCP

  • 客户端
    1.连接服务器Socket
    2.发送消息
    3.关闭资源
  • 服务器端
    1.建立服务的端口ServerSocket
    2.等待用户的连接 accept
    3.接受用户的消息
    4.关闭资源
    客户端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

//客户端
public class TcpClientDemo01 {
    public static void main(String[] args) throws Exception {

        //创建Socket连接
        //要知道服务器端的地址和端口号
        InetAddress serverIP = InetAddress.getByName("127.0.0.1");
        int port = 8888;

        //创建Socket连接
        Socket socket = new Socket(serverIP, port);

        //发送消息  IO流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("欢迎学习java".getBytes());

        //关闭资源
          //baos.close();
//        is.close();
        socket.close();
        outputStream.close();
    }
}

服务器端

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

//用户端
public class TcpServerDemo01 {

    public static void main(String[] args) throws Exception {
        //建立连接
        //自己的端口号
        ServerSocket serverSocket = new ServerSocket(8888);

        //接受Socket连接  等待客户的连接
        Socket socket = serverSocket.accept();

        //接受消息
        InputStream inputStream = socket.getInputStream();

        //管道流----缓冲
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }

        System.out.println(baos.toString());

        //关闭资源
        baos.close();
        inputStream.close();
//        os.close();
        socket.close();
        serverSocket.close();
    }

输出结果
TCP和UDP实现聊天_第1张图片

UDP

发送消息不用连接,只需知道对方的地址,接收时只需要接收消息。以数据报的形式发送信息。


发送端

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UdpSenderDemo01 {
    public static void main(String[] args) throws Exception{
        DatagramSocket socket = new DatagramSocket(8888);

        //准备数据,控制台读取 System.in
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        while (true){
            String data = bufferedReader.readLine();
            byte[] datas = data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
            socket.send(packet);

            System.out.println(packet);

            if (data.equals("bye")){
                break;
            }
        }

        socket.close();
    }
}

接收端

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpReceiverDemo01 {
    public static void main(String[] args) throws Exception{
        DatagramSocket datagramSocket = new DatagramSocket(6666);

        while (true){
            //准备接收包裹
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
            datagramSocket.receive(packet);  //阻塞式接受包裹

            //断开连接
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);

            System.out.println(receiveData);

            if (receiveData.equals("bye")){
                break;
            }
        }

        datagramSocket.close();

    }
}

你可能感兴趣的:(tcp/ip,udp,网络,java)