Socket网络编程

数据在两个socket当中通过io流进行传播

Untitled

入门案例1

Untitled

服务端代码:

public class Server1 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        byte[] buffer = new byte[2];
        Socket client = serverSocket.accept();
        // 读取输入端的数据
        InputStream inputStream = client.getInputStream();
        // 循环读取数据
        int l = 0;
        while((l = inputStream.read(buffer)) != -1) {
            for (int i = 0; i < l; i++) {
                System.out.printf("%c",(char)buffer[i]);
            }
        }
        System.out.println();
    }
}

客户端代码:(客户端也可以直接用nc进行连接)

public class Client1 {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 9999);
        // 写入数据
        socket.getOutputStream().write("hello world".getBytes());
        socket.close();
    }
}

入门案例2

Untitled

这个案例学会:发完消息要发送消息边界:socket.shutdownOutput()

服务端代码:

public class Server2 {
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket serverSocket = new ServerSocket(9999);
        byte[] buffer = new byte[256];
        Socket client = serverSocket.accept();
        // 读取输入端的数据
        InputStream inputStream = client.getInputStream();
        // 循环读取数据
        int readLine = 0;
        while((readLine = inputStream.read(buffer)) != -1) {
            for (int i = 0; i < readLine; i++) {
                System.out.printf("%c",(char)buffer[i]);
            }
        }
        System.out.println("------> "+ readLine);

        // 发送消息和消息边界
        OutputStream outputStream = client.getOutputStream();
        outputStream.write("hello, client".getBytes());
        client.shutdownOutput();

        outputStream.close();
        client.close();
        serverSocket.close();
    }
}

客户端代码:

public class Client2 {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 9999);
        byte[] buffer = new byte[128];
        // 写入数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello world".getBytes());
        // 发送消息边界
        socket.shutdownOutput();

        int l = socket.getInputStream().read(buffer);
        for (int i = 0; i < l; i++) {
            System.out.printf("%c", (char)buffer[i]);
        }
        System.out.println();
        socket.close();
    }
}

入门案例3——字符流

使用字符流比直接使用字节流更加方便

Untitled

服务端:注意发送结束后一定要加上newLine() 和 flush()