从本地计算机连接到 ServerSocket
我对 java 相当陌生,目前正在尝试套接字和缓冲区。
我想尝试的只是实例化一个本地 java 应用程序和另一个本地 java 应用程序的连接。我正在使用 ServerSocket 和 Socket。
服务器应用程序有一个侦听连接的线程:
public void run() {
try{
ServerSocket serverSock = new ServerSocket(62666);
while(doRun){
Socket sock = serverSock.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
InfoReader.gui.writeToTextArea(reader.readLine() + "\n");
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
“客户端”只是将一个字符串发送到服务器(应该是这样,但我无法使其工作):
try{
Socket sock = new Socket("127.0.0.1",62666);
PrintWriter writer = new PrintWriter(sock.getOutputStream());
writer.print("Connection works!");
}catch(IOException e){
e.printStackTrace();
}
我确信端口已打开并转发到本地机器已经。我检查过 http://canyouseeme.org/。
我还尝试使用我的外部 IP 地址作为客户端中套接字的 IP。它也不起作用。
任何帮助表示赞赏:)。
麦克风。
I am fairly new to java and I am currently experimenting with sockets and buffers.
What I wanted to try was just to instantiate a connection from one local java app and another. I am using ServerSocket and Socket.
The server app has a thread that listens for connections:
public void run() {
try{
ServerSocket serverSock = new ServerSocket(62666);
while(doRun){
Socket sock = serverSock.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
InfoReader.gui.writeToTextArea(reader.readLine() + "\n");
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
The "client" simply sends a string to the server (well it should, but I can't make it work):
try{
Socket sock = new Socket("127.0.0.1",62666);
PrintWriter writer = new PrintWriter(sock.getOutputStream());
writer.print("Connection works!");
}catch(IOException e){
e.printStackTrace();
}
I am sure that the port is open and forwarded to the local machine already. I've checked on http://canyouseeme.org/.
I've also tried using my external IP address as the IP of the socket in the client. It did not work either.
Any help appreciated :).
Mike.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,然后作为答案,这样您就可以关闭问题;-)
向 Writer 添加一个flush()和一个close()。
希望有帮助。 :-)
Ok, then as an answer so you can close the question ;-)
Add a flush() and a close() to the Writer.
Hope that helps. :-)