Java Socket Programming(Java 套接字编程)
问题描述
我正在使用 java 套接字构建一个简单的客户端/服务器应用程序并尝试使用 ObjectOutputStream 等.
I am building a simple client/server application using java sockets and experimenting with the ObjectOutputStream etc.
我一直在关注这个网址上的教程 http://java.sun.com/developer/technicalArticles/ALT/sockets 在谈到通过套接字传输对象时从一半开始.
I have been following the tutorial at this url http://java.sun.com/developer/technicalArticles/ALT/sockets starting half way down when it talks about transporting objects over sockets.
查看我的客户端代码 http://pastebin.com/m37e4c577 但是这似乎不起作用,我无法弄清楚什么不起作用.底部注释掉的代码是直接从教程中复制出来的——当我只使用它而不是创建客户端对象时,这很有效.
See my code for the client http://pastebin.com/m37e4c577 However this doesn't seem to work and i cannot figure out what's not working. The code commented out at the bottom is directly copied out of the tutorial - and this works when i just use that instead of creating the client object.
谁能看到我做错了什么?
Can anyone see anything i am doing wrong?
推荐答案
问题是你创建流的顺序:
The problem is the order you are creating the streams:
在文章中的服务器(我假设您正在使用的服务器)中,当打开新连接时,服务器首先打开一个输入流,然后打开一个输出流:
In the server from the article (which I assume is what you are using), when a new connection is opened, the server opens first an input stream, and then an output stream:
public Connect(Socket clientSocket) {
client = clientSocket;
try {
ois = new ObjectInputStream(client.getInputStream());
oos = new ObjectOutputStream(client.getOutputStream());
} catch(Exception e1) {
// ...
}
this.start();
}
注释的示例代码使用相反的顺序,先建立输出流,再建立输入流:
The commented example code uses the reverse order, first establishing the output stream, then the input stream:
// open a socket connection
socket = new Socket("localhost", 2000);
// open I/O streams for objects
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
但你的代码却反过来:
server = new Socket(host, port);
in = new ObjectInputStream(server.getInputStream());
out = new ObjectOutputStream(server.getOutputStream());
建立一个输出流/输入流对将停止直到他们交换了他们的握手信息,所以你必须匹配创建的顺序.您只需在示例代码中交换第 34 行和第 35 行即可.
Establishing an output stream/input stream pair will stall until they have exchanged their handshaking information, so you must match the order of creation. You can do this just by swapping lines 34 and 35 in your example code.
这篇关于Java 套接字编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 套接字编程
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01