【发布时间】:2016-08-31 17:53:00
【问题描述】:
我正在尝试学习 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
客户端和服务器都在我的笔记本电脑上运行,通过以太网连接到大学的互联网连接,如果有帮助的话。
【问题讨论】:
标签: java sockets network-programming inputstream blocking