如何在JAVA中使用套接字在服务器和客户端之间进行双向通信?

How to do 2 way communication between server and client using sockets in JAVA?

提问人:PROMAN8625 提问时间:11/15/2022 最后编辑:PROMAN8625 更新时间:11/17/2022 访问量:213

问:

我做了 2 节课,一堂是,一堂是.我用来在他们之间交流。服务器和客户端连接但不发送数据并保持连接状态。client.javaserver.javasocket

client.java:

public static void main(String[] args) throws Exception {
  Socket s = new Socket("localhost", 42069);
  System.out.println("Connected to the server!");
        
  BufferedWriter out = new BufferedWriter
      (new OutputStreamWriter(s.getOutputStream()));

  BufferedReader in = new BufferedReader
      (new InputStreamReader(s.getInputStream()));
        
  out.write("hi from client");
  System.out.println(in.readLine());
        
  s.close();
}

server.java:

public static void main(String[] args) throws Exception {               
  ServerSocket ss = new ServerSocket(42069);
  System.out.println("\nWaiting For Connection...");
  Socket s = ss.accept();
  System.out.println("\nConnected to the client!");
            
  BufferedReader in = new BufferedReader
      (new InputStreamReader(s.getInputStream()));

  BufferedWriter out = new BufferedWriter
      (newOutputStreamWriter(s.getOutputStream()));
            
  System.out.println(in.readLine());
  out.write("hi from server");
            
}

当两者连接时,它们会保持如下状态:s.jaerverva


Waiting For Connection...

Connected to the client!

client.java

Connected to the server!

当我终止客户端时,我在服务器上收到以下错误:

Exception in thread "main" java.net.SocketException: Connection reset
    at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:323)
    at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
    at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
    at java.base/java.net.Socket$SocketInputStream.read(Socket.java:966)
    at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:270)
    at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:313)
    at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:188)
    at java.base/java.io.InputStreamReader.read(InputStreamReader.java:177)
    at java.base/java.io.BufferedReader.fill(BufferedReader.java:162)
    at java.base/java.io.BufferedReader.readLine(BufferedReader.java:329)
    at java.base/java.io.BufferedReader.readLine(BufferedReader.java:396)
    at HTTP.server.main(server.java:14)

Java 套接字网络 IO java-stream

评论

0赞 PROMAN8625 11/15/2022
你说的URLConnection.openStream()是什么意思,我没有理解它。
0赞 ControlAltDel 11/15/2022
对不起,正确的方法是 URLConnection.getOutputStream()
0赞 ControlAltDel 11/15/2022
顺便说一句,我强烈建议您使用 Websockets 而不是普通的旧 Sockets。Websockets 为您处理如此多的管道。
0赞 PROMAN8625 11/15/2022
你能解释一下吗?URLConnection.getOutputStream()

答: 暂无答案