Socket 练习

服务器端:
package com.h;

import java.net.*;
import java.io.*;

public class SimpleServer {
    private ServerSocket ss;
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    public SimpleServer() {
        try {
            ss = new ServerSocket(9001);
            //设置等待的时间
            ss.setSoTimeout(6000);
            while (true) {
                socket = ss.accept();
                //获取链接的远程IP
                String RemoteIP = socket.getInetAddress().getHostAddress();
                //获取链接的端口
                String RemotePort = ":" + socket.getLocalPort();
                System.out.println("有一个客户端链接进来!IP:" + RemoteIP + RemotePort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
               
                String line = in.readLine();
                System.out.println("客户端发送的内容是 :" + line);
                out = new PrintWriter(socket.getOutputStream(), true);
                out.println("您的消息已经接收到");
                out.close();
                in.close();
                socket.close();
            }
        } catch (IOException e) {
            out.println("wrong");
        }
    }

    public static void main(String[] args) {
        new SimpleServer();
    }
}

客户端
package com.h;
import java.io.*;
import java.net.*;

public class SimpleClient {
    Socket socket;
    BufferedReader in;
    PrintWriter out;

    public SimpleClient() {
        try {
            System.out.println("尝试链接到 127.0.0.1:9001");
            //与服务器端建立链接
            socket = new Socket("127.0.0.1", 9001);
            System.out.println("已经与服务器端建立链接");
            System.out.println("请输入要传输的信息:");
            //从页面上接收输入
            BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(socket.getOutputStream(), true);
            out.println(line.readLine());
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println(in.readLine());
            out.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            out.println("发生错误");
        }
    }

    public static void main(String[] args) {
        new SimpleClient();
    }
}

你可能感兴趣的:(java,.net,socket)