2011-11-12 83 views
3

我试图写一个客户机/服务器程序,客户端可以: *将一个字符串写入服务器 *从服务器Java套接字:如何读取/写入对象和字符串?

,接收对象和服务器可以: *从客户端 接收一个字符串*发送一个对象给客户端。

不过,我迄今为止的尝试已经证明是徒劳的,我很沮丧。我确信我正在犯一个基本的缺陷,但是对于Socket编程来说,这是一件很新的事情,我只是无法知道我出错的地方。

我的流选择有什么问题吗?还是有更好的方式来使用我还没有找到的流?

我送的对象序列化,尽管该对象不会被写入/读取的服务器挂在的readUTF()

预先感谢您的任何帮助。

//Used to receive a string input from client side 
DataInputStream input = new DataInputStream(clientSocket.getInputStream()); 
// Used to output an object to client side 
ObjectOutputStream oo = new ObjectOutputStream(clientSocket.getOutputStream()); 

// This is never executed.. 
clientInput = input.readUTF(); 
oo.writeObject(book); 

客户端代码:

 // Used to read object from server side 
     input = new ObjectInputStream(clientSocket.getInputStream()); 
     // Used to read input from command line 
     keyboard = new BufferedReader(new InputStreamReader(System.in)); 
     // Used to send string to server 
     output = new DataOutputStream(clientSocket.getOutputStream()); 

     cmdInput = keyboard.readLine(); 
     // Write to server, this executes at runtime. 
     output.writeUTF(cmdInput);        
     // Object is never sent, this line is not executed. 
     book = (Book)input.readObject(); 
+0

由于您使用ObjectInputStream和ObjectOutputStream,我假设您想使用TCP。你可以在你为服务器和客户端创建clientSocket的地方包含代码吗?您正在使用服务器的ServerSocket类,对吗? –

+0

是的我正在使用ServerSocket服务器和客户端的套接字。客户端服务器连接工作正常,因为我能够简单地传递字符串。这是当我添加对象功能,它开始打破。 – BodhiByte

+0

但是在你调用writeObject之前你的客户端代码被卡住了...... –

回答

0

一般情况下,你会使用web服务套件(例如Apache的CXF)比这样做自己会更好。

具体而言,请尝试在客户端的输出流上调用flush()

+0

我已经尝试在客户端调用flush,它没有做任何改变。另外,对于这个问题,我只适合在JDK库中开发。 – BodhiByte

+0

在java 1.6中,JDK中有一个完整的Web服务工具包。 – bmargulies