Java 套接字编程

Java Socket Programming(Java 套接字编程)

本文介绍了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 套接字编程

基础教程推荐