[英]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.