TCP(socket 套接字)编程 1-二、相关代码实现

时间:2024-03-27 13:46:49

1、服务器端代码

package com.company;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {

    public static void main(String[] args) {
// write your code here

        try {
            //创建服务,并监听特定的端口,设置TCP链接队列长度
            //backlog可以设置队列的长度,成功创建链接的会被存储到此全连接队列中,等待线程调用accept方法将其从中一个一个移出
            ServerSocket serverSocket = new ServerSocket(8081,3);
            System.out.println("服务开始进行监听,监听端口为8081");
            int i=1;
            while(true){
                //从全连接队列中移出一个连接
                Socket socket = serverSocket.accept();
                byte[] byet1=new byte[20];
                try {
                    socket.getInputStream().read(byet1);
                    String str =new String(byet1);
                    System.out.println(str);
                    InetSocketAddress  socketAddress=(InetSocketAddress)socket.getRemoteSocketAddress();
                    System.out.println(socketAddress.getHostName()+"   "+socketAddress.getPort());
                    //socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    Thread.sleep(50000);
                    socket.close();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}
  • 1、创建服务,并监听特定的端口,设置TCP链接队列长度;
  • 2、backlog可以设置队列的长度,成功创建链接的会被存储到此全连接队列中,等待线程调用accept方法将其从中一个一个移出;

2、客户端代码

package com.company;

import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        // write your code here
        byte [] byte2= new byte[20];
        int i=1;
        String string="hello world";
        for(;i<3;i++){
        try {
            String str=string+i;
            byte2= string.getBytes(StandardCharsets.UTF_8);
            Socket socket =new Socket("127.0.0.1",8081);
            System.out.println(socket.getLocalAddress().getHostAddress()+"   "+socket.getLocalPort());
            socket.setKeepAlive(true);
            System.out.println(str);
            socket.getOutputStream().write(byte2);
            Thread.sleep(10000);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        }
    }
}