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 套接字编程
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01