问题
I'm building a client-server project.
What I need is that the client sends a string, such as "Pendu", and the server receives this string and send an object named "Pendu" back to the client.
Here is my code:
// 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");
The class Pendu
is defined in the package 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";
}
}
My problem is:
First I execute the server and I can see that accepting...
is shown in the console.
Then I execute the client, in the console I get messages as below:
sending...
sent
receiving...
At the same time, nothing new is shown at the server side.
Now I stop the client and all other messages of the server are shown:
Received from client: Pendu
building object...
object built
Of course I get also the error:
java.net.SocketException: Broken pipe
This is logical because I kill the client which hasn't finish receiving.
I don't know why the client can't receive as expected.
回答1:
You are reading lines but not writing lines. You need to add a line terminator to the "Pendu"
message.
NB When you send a Pendu
, why are you sending a new one instead of the one you just created?
来源:https://stackoverflow.com/questions/42881425/socket-readline-doesnt-receive-line-sent