gpt4 book ai didi

Java SocketServer 正在接受来自 Socket 客户端的输入,但 Socket 客户端未接收来自 SocketServer 的输入

转载 作者:行者123 更新时间:2023-12-01 09:32:50 30 4
gpt4 key购买 nike

我正在尝试学习 Java 网络编程,但遇到了一些障碍。我已经编写了服务器和客户端,但每次尝试连接它们时,我都会立即收到连接关闭错误。然后,我尝试编辑它,但现在出现连接拒绝错误。放弃了这一点,我决定在一个非常简单的服务器上工作来测试 Sockets 和 ServerSockets 的基础知识。这样做,我想出了这两个类:

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class SimpleServer {
public static void main(String[] args) throws Exception {
System.out.println("hey there");
ServerSocket server = new ServerSocket(50010);
Socket socket = server.accept();
System.out.println("Connection at " + socket);

InputStream in = socket.getInputStream();
int c = 0;
while ((c = in.read()) != -1) {
System.out.print((char)c);
}


OutputStream out = socket.getOutputStream();
for (byte b : (new String("Thanks for connecting!")).getBytes()) {
out.write(b);
out.flush();
}

in.close();
out.close();
socket.close();
server.close();
}
}

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

public class SimpleClient {
public static void main(String[] args) throws Exception {
System.out.println("Attempting connection");
Socket s = new Socket("130.49.89.208", 50010);
System.out.println("Cool");

OutputStream out = s.getOutputStream();
for (byte b : (new String("Hey server\r\nThis message is from the client\r\nEnd of message\r\n")).getBytes()) {
out.write(b);
out.flush();
}

InputStream in = s.getInputStream();
int c = 0;
System.out.println("this message will print");
while ((c = in.read()) != -1) {
System.out.print((char)c);
System.out.println("this does not print");
}

out.close();
in.close();
s.close();
}
}

服务器完全正常地接收客户端的消息,但是当轮到服务器向客户端写入消息时,一切都会阻塞。

服务器的输出:

-java SimpleServer 
----hey there
----Connection at Socket[addr=/130.49.89.208,port=59136,localport=50010]
----Hey server
----This message is from the client
----End of message

客户端的输出:

-java SimpleClient
----Attempting connection
----Cool
----this message will print

客户端和服务器都在我的笔记本电脑上运行,通过以太网连接到大学的互联网连接,如果有帮助的话。

最佳答案

根据 Javadocs,InputStream.read() 描述为:

If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

在您的情况下,中断 while 循环的唯一可能是客户端关闭连接,从而导致流结束。

根据您的编码,这是预期的!

关于Java SocketServer 正在接受来自 Socket 客户端的输入,但 Socket 客户端未接收来自 SocketServer 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39256069/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com