我正在构建一个客户端 - 服务器项目
我需要的是客户端发送一个字符串,例如" Pendu",服务器接收该字符串并发送一个名为" Pendu"的对象。回到客户端。
这是我的代码:
// server
ServerSocket serverSocket = new ServerSocket(6789);
System.out.println("accepting...");
Socket socket = serverSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ObjectOutputStream outToClient = new ObjectOutputStream(socket.getOutputStream());
String clientMsg = inFromClient.readLine();
System.out.println("Received from client: " + clientMsg);
Object obj;
System.out.println("building object...");
obj = Class.forName("Data." + clientMsg).newInstance();
System.out.println("object built");
if(obj instanceof Pendu)
{
System.out.println("Send to client: " + obj);
outToClient.writeObject(new Pendu());
}
//client
Socket socket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
System.out.println("sending...");
outToServer.writeBytes("Pendu");
System.out.println("sent");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
System.out.println("receiving...");
Object obj = ois.readObject(); // it is blocked here and I don't know why
System.out.println("received");
课程Pendu
在课程Data
中定义:
package Data;
public class Pendu implements Serializable
{
private static final long serialVersionUID = 1L;
private static String[] words = new String[]{"bonjour", "bonsoir", "hier", "france", "ordinateur"};
private static Random rand = new Random();
private String but;
public Pendu()
{
this.but = words[rand.nextInt(words.length)];
}
public int getLenth()
{
return this.but.length();
}
public String getBut()
{
return this.but;
}
@Override
public String toString()
{
return "I'm a pendu object";
}
}
我的问题是:
首先我执行服务器,我可以看到控制台中显示accepting...
然后我执行客户端,在控制台中我得到如下信息:
sending...
sent
receiving...
同时,服务器端没有显示任何新内容
现在我停止客户端并显示服务器的所有其他消息:
Received from client: Pendu
building object...
object built
当然我也得到了错误:
java.net.SocketException:Broken pipe
这是合乎逻辑的,因为我杀死了没有完成接收的客户 我不知道为什么客户无法按预期收到。
答案 0 :(得分:0)
你正在读行而不是写行。您需要在"Pendu"
消息中添加行终止符。
注意当您发送Pendu
时,为什么要发送一个新的而不是刚创建的那个?