Java套接字编程 [英] Java Socket Programming

查看:124
本文介绍了Java套接字编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用java套接字构建一个简单的客户端/服务器应用程序并尝试使用ObjectOutputStream等。

I am building a simple client/server application using java sockets and experimenting with the ObjectOutputStream etc.

我一直在关注此url的教程 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());

但是你的代码是相反的:

But your code does it the other way around:

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套接字编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆