美文网首页
java socket

java socket

作者: 谢贤byte | 来源:发表于2020-10-10 14:46 被阅读0次

    客户端

    public class Client {
        public static void main(String[] args) {
            String serverName = "localhost";
            int port = 8080;
            try {
                System.out.println("连接到主机:" + serverName + " ,端口号:" + port);
                Socket client = new Socket(serverName, port);
                System.out.println("远程主机地址:" + client.getRemoteSocketAddress());
                OutputStream outToServer = client.getOutputStream();
                DataOutputStream out = new DataOutputStream(outToServer);
    
                out.writeUTF("Hello from " + client.getLocalSocketAddress());
                InputStream inFromServer = client.getInputStream();
                DataInputStream in = new DataInputStream(inFromServer);
                System.out.println("服务器响应: " + in.readUTF());
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    服务端

    public class Server extends Thread {
        private ServerSocket serverSocket;
    
        public Server(int port) throws IOException {
            serverSocket = new ServerSocket(port);
            serverSocket.setSoTimeout(100000);
        }
    
        public void run() {
            while (true) {
                try {
                    System.out.println("等待远程连接,端口号为:" + serverSocket.getLocalPort() + "...");
                    Socket server = serverSocket.accept();
                    System.out.println("远程主机地址:" + server.getRemoteSocketAddress());
                    DataInputStream in = new DataInputStream(server.getInputStream());
                    System.out.println(in.readUTF());
                    DataOutputStream out = new DataOutputStream(server.getOutputStream());
                    out.writeUTF("谢谢连接我:" + server.getLocalSocketAddress());
                    server.close();
                } catch (SocketTimeoutException s) {
                    System.out.println("Socket timed out!");
                    break;
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    
        public static void main(String[] args) {
            int port = 8080;
            try {
                Thread t = new Server(port);
                t.run();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:java socket

          本文链接:https://www.haomeiwen.com/subject/vtqrpktx.html