java socket单线程阻塞IO

很久没有写blog了,偶尔想写一下java socket的小程序,发现无法上手了。捉急,遂下定决定复习一下!

首先来一个单线程的阻塞IO的代码:

Server.java代码如下:

package com.test.socket;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(9527), 10);
        while(true) {
            try {
                Socket clientSocket = serverSocket.accept();
                clientSocket.setTcpNoDelay(true);
                clientSocket.setReuseAddress(true);
                
                BufferedReader bufReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
                
                System.out.println(clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort() + " received!");
                String line = bufReader.readLine();
                System.out.println(clientSocket.getInetAddress().getCanonicalHostName() + " say:" + line);
                
                writer.println("received '" + line + "'");
                writer.flush();
                clientSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

代码很简单,打印客户端发送的字符串。

编译:javac -d ./ Server.java

运行:java com/test/socket/Server

查看端口状态:netstat -ntpl  | grep 9527 (此时端口应该处于LISTEN状态下


客户端Client.java代码如下:

package com.test.socket;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 9527);
        socket.setTcpNoDelay(true);
        
        PrintWriter out = new PrintWriter(socket.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out.println("hello world");
        out.flush();    //必须flush,服务端无法收到消息
        
        String line = reader.readLine();
        System.out.println("server say : " + line);
        
        socket.close();
    }
}

编译:javac -d ./ Client.java

运行:java com/test/socket/Client

可以看到服务器端可以显示出客户端发送的字符串。

注:此Server和Client可以运行在不同的主机不同的操作系统之间。



你可能感兴趣的:(java基础,socket,java)