Java Sockets编程示例代码

windows cmd命令行查看当前SOCKET使用的端口号命令:

netstat -ano | findstr "10001"
package com.example.orange;

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

public class SocketDemo {
    public static void main(String[] args) {
        new Thread(() -> {
            new Server();
        }).start();
        new Thread(() -> {
            new Client();
        }).start();
    }
}

class Server {
    private ServerSocket ss;
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private static final String TAG = "Server: ";

    public Server() {
        try {
            ss = new ServerSocket(10001);
            while (true) {
                socket = ss.accept();
                String RemoteIP =
                        socket.getInetAddress().getHostAddress();
                String RemotePort = ":" + socket.getLocalPort();
                // 获取到连接server的client
                System.out.println(TAG + "A client come in! IP:" + RemoteIP + RemotePort);
                // 读取到client发送的字符
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line = in.readLine();
                System.out.println(TAG + "Client has sent : " + line);
                
                // 给client回复
                out = new PrintWriter(socket.getOutputStream(), true);
                out.println("Your Message Received!");

                out.close();
                in.close();
                socket.close();
            }
        } catch (IOException e) {
            out.println("wrong");
        }
    }
}

class Client {
    Socket socket;
    BufferedReader in;
    PrintWriter out;
    private static final String TAG = "Client: ";

    public Client() {
        try {
            while (true) {
                System.out.println(TAG + "Try to Connect to 127.0.0.1:10001");
                // client创建连接
                socket = new Socket("127.0.0.1", 10001);
                System.out.println(TAG + "The Server Connected!");
                System.out.println(TAG + "Please enter some Character:");
                // client读取标准输入发送给server
                BufferedReader line = new BufferedReader(new
                        InputStreamReader(System.in));
                out = new PrintWriter(socket.getOutputStream(), true);
                out.println(line.readLine());
                // 读server的回复 如果是远程的server没这么快
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                System.out.println(TAG + in.readLine());

                out.close();
                in.close();
                socket.close();
            }

        } catch (IOException e) {
            out.println("Wrong");
        }
    }
}


你可能感兴趣的:(Java Sockets编程示例代码)