• TCP编程


    Server.java

    package com.zby;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class Server {
        private static boolean running = true;
    
        public static void main(String[] args) throws Exception {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("LocalSocketAddress:" + serverSocket.getLocalSocketAddress());
            System.out.println("----------------------------------------------------------");
            while (running) {
                Socket socket = serverSocket.accept();
                System.out.println("connected!");
                System.out.println("RemoteSocketAddress:" + socket.getRemoteSocketAddress());
    
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                String request = dataInputStream.readUTF();
                System.out.println("request:" + request);
    
                String response = "Hello,Client!";
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeUTF(response);
                System.out.println("response:" + response);
    
                System.out.println("disConnected!");
                System.out.println();
                socket.close();
            }
            serverSocket.close();
        }
    
    }

    Client.java

    package com.zby;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.net.InetAddress;
    import java.net.Socket;
    
    public class Client {
    
        public static void main(String[] args) throws Exception {
            Socket socket = new Socket(InetAddress.getLocalHost(), 8888, InetAddress.getLocalHost(), 7777);
            System.out.println("connected!");
            System.out.println("LocalSocketAddress:" + socket.getLocalSocketAddress());
            System.out.println("RemoteSocketAddress:" + socket.getRemoteSocketAddress());
            System.out.println();
    
            String request = "Hello,Server!";
            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.writeUTF(request);
            System.out.println("request:" + request);
    
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            String response = dataInputStream.readUTF();
            System.out.println("response:" + response);
            System.out.println("disConnected!");
            socket.close();
        }
    
    }
  • 相关阅读:
    Object的原型拷贝-create、assign、getPrototypeOf 方法的结合
    配intelliJ IDEA 过程
    浅谈HTTP中Get与Post的区别
    apply、call、bind区别、用法
    引用类型与原始类型的区别
    html5标签集结1
    指针作为参数传递
    指针与指针变量
    函数模板
    内置函数
  • 原文地址:https://www.cnblogs.com/zby9527/p/7651671.html
Copyright © 2020-2023  润新知