[英]Java Client/Server chat room sending messages as objects
我的目标是创建一个服务器,该服务器从ObjectInputStream接收Message对象,然后将该Message对象回显到ObjectOutputStream。
编写消息后,客户端将消息类型对象发送到服务器,然后接收到的消息类型对象(以及来自连接到服务器的其他客户端的消息类型对象)并将其解码为客户端的gui。
Message对象具有字符串和其他字体信息。
我的问题是服务器不会回显消息类型对象。 我觉得自己的表现不正确,但此时我只是在尝试不同的东西。
想法是使服务器对客户端透明-这是否可能,即:服务器对TestObject类一无所知? 有没有解决的办法?
服务器代码:
import java.net.*;
import java.io.*;
public class Server
{
public SimpleServer() throws IOException, ClassNotFoundException
{
ServerSocket ss = new ServerSocket(4000);
Socket s = ss.accept();
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
// the 'echo' functionality of the server
Object to = null;
try
{
to = ois.readObject();
}
catch (ClassNotFoundException e)
{
System.out.println("broke");
e.printStackTrace();
}
oos.writeObject(to);
oos.flush();
// close the connections
ois.close();
oos.close();
s.close();
ss.close();
}
public static void main(String args[]) throws IOException, ClassNotFoundException {
new SimpleServer();
}
}
客户代码:
import java.net.*;
import java.io.*;
public class Client
{
public SimpleClient() throws IOException, ClassNotFoundException
{
Socket s = new Socket( "localhost", 4000 );
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream( s.getInputStream());
TestObject to = new TestObject( 1, "object from client" );
// print object contents
System.out.println( to );
oos.writeObject(to);
oos.flush();
Object received = ois.readObject();
// should match original object contents
System.out.println(received);
oos.close();
ois.close();
}
public static void main(String args[]) throws IOException, ClassNotFoundException
{
new SimpleClient();
}
}
class TestObject implements Serializable
{
int value ;
String id;
public TestObject( int v, String s )
{
this.value=v;
this.id=s;
}
@Override
public String toString()
{
return "value=" + value +
", id='" + id;
}
}
感谢您的时间!
编辑:这是创建的输出:
当客户端连接到服务器时,我收到此消息:线程“ main”中的异常java.lang.ClassNotFoundException:TestObject
这是我运行客户端时的客户端输出:value = 1,id ='object from client线程“主”中的异常java.net.SocketException:连接重置
第一件事: TestObject
类在您的服务器代码中不可见。 这就是为什么它抛出ClassNotFoundException
。
解决方案:将TestObject
类放在单独的文件中,然后使用import
语句导入该类。
第二:尝试在服务器端打印接收到的对象的值。 并对客户代码进行如下更改
Object received = null;
while(received==null)
{
received = ois.readObject();
}
System.out.println(received);
我看不到您的代码有任何问题,除了在服务器和客户端中都写入oos
流之后,您需要刷新它。
oos.flush();
同样,为了使服务器对客户端透明,您可以避免在服务器上进行强制转换(这已经在做),并且端点应担心作为客户端的TestObject
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.