美文网首页
Tomcat 单播通信

Tomcat 单播通信

作者: 吉林天师 | 来源:发表于2020-01-15 04:21 被阅读0次

    客户端

    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class SocketClient {
    
        public static void main(String[] args) {
            Socket socket = null;
    
            try {
    
                socket = new Socket("localhost", 8888);
    
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                DataInputStream dis = new DataInputStream(socket.getInputStream());
    
                dos.writeUTF( "我是客户端,请求连接");
                System.out.print(dis.readUTF());
    
                socket.close();
    
            }catch (UnknownHostException e){
    
                    e.printStackTrace();
    
            }catch (IOException e){
    
                e.printStackTrace();
            }
        }
    }
    
    

    服务端

    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class SocketServer {
        public static void main(String[] args) {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(8888);
                Socket socket = serverSocket.accept();
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                DataInputStream dis = new DataInputStream(socket.getInputStream());
                System.out.print("服务器收到客户端的来链接请求"+ dis
                        .readUTF());
                dos.writeUTF("接受连接请求成功!");
                socket.close();
                serverSocket.close();
    
            }catch (
                    IOException e){
                e.printStackTrace();
            }
        }
    }
    
    

    在终端执行命令

    javac SocketServer.java
    
    java SocketServer
    
    javac SocketClient.java
    
    java SocketClient
    

    相关文章

      网友评论

          本文标题:Tomcat 单播通信

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