I am writing a server for a game which I am coding in java. The output stream won't actually send the information back to the client for some reason. I have tried everything, however closing the socket ends up in the program erroring because of the socket closing before it has written to the output stream. I am unable to figure out why.
EDIT: I have put a lot of the code in this gist . Also, for clarification, the response wasn't sending at all, even if I didn't close the socket. The client was simply waiting for an answer, and not receiving one.
Here is my code.
public class ServerThread extends Thread {
private Socket clientSocket;
private List<Player> players;
public Player player = null;
public ServerThread (Socket clientSocket, List<Player> players)
{
this.clientSocket = clientSocket;
this.players = players;
}
public void run()
{
try {
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream os = new DataOutputStream(clientSocket.getOutputStream());
String req = br.readLine();
br.close();
String response = buildResponse(req);
os.writeBytes(response);
os.flush();
System.out.println("Sending [ " + response + " ] to " + clientSocket.getInetAddress().getHostAddress());
player = addPlayerFromRequest(req);
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
try {
clientSocket.close();
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String buildResponse(String req)
{
List<Player> plays;
plays = players;
String name = req.split(",")[0];
String response = "";
if (plays.size() <= 1) {
return response;
}
for (int i = 0; i < plays.size(); i++) {
Player p = plays.get(i);
if (!p.name.equals(name)) {
response += p.name + "," + p.x + "," + p.y + "," + p.z + "," + p.rx + "," + p.rx + "," + p.rz + ";";
}
}
return response;
}
public Player addPlayerFromRequest (String req)
{
String[] list = req.split(",");
String user = list[0];
float x = Float.parseFloat(list[1]);
float y = Float.parseFloat(list[2]);
float z = Float.parseFloat(list[3]);
float rx = Float.parseFloat(list[4]);
float ry = Float.parseFloat(list[5]);
float rz = Float.parseFloat(list[6]);
return new Player(x, y, z, rx, ry, rz, user);
}
}
This code will throw SocketException: Socket closed
because of br.close()
, but assuming you've removed that, I suggest that your client is reading lines but you aren't sending lines. Add a line terminator to the message, or use BufferedWriter.newLine()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.