BSD Socket (java)

服务器

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {

        ServerSocket ss = new ServerSocket(10000);
        System.out.println("伺服中.......");
        while (true) {
            // The method blocks until a connection is made.
            // 阻塞直至建立某个连接
            Socket s = ss.accept();

            // 接收数据
            InputStream in = s.getInputStream();
            byte[] b = new byte[1024 * 1024];
            int len = in.read(b);
            String requestData = new String(b, 0, len);
            System.out.println("客户端请求数据:" + requestData);

            // 处理数据
            String responseData = requestData.toUpperCase();

            // 响应结果
            OutputStream out = s.getOutputStream();
            out.write(responseData.getBytes());

            in.close();
            out.close();
            s.close();

            // 关闭服务
            if (requestData.equalsIgnoreCase("exit")) {
                break;
            }
        }
        ss.close();
    }
}

客户端

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

    public static void main(String[] args) throws UnknownHostException,
            IOException {
        Socket s = new Socket("172.16.162.238", 10000);

        // 发起请求
        OutputStream out = s.getOutputStream();
        out.write(args[0].getBytes());

        // 接收处理结果
        InputStream in = s.getInputStream();
        byte[] b = new byte[1024 * 1024];
        int len = in.read(b);
        String result = new String(b, 0, len);
        System.out.println("处理结果是:" + result);

        in.close();
        out.close();
        s.close();

    }

}

测试:

客户端请求参数

Program arguments:abc

客户端显示结果:

处理结果是:ABC

服务器显示结果:

伺服中.......
客户端请求数据:abc

注意:

accept方法会加锁,直到建立连接。

多个客户端连接服务器时,需排队依次处理。

原文地址:https://www.cnblogs.com/zno2/p/4642671.html