Reputation: 5897
I'm trying to send some data from a client to a server using Java, here is my PlayerThread which is ran on the server when a new client connects
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
//Create a link to send data to the server
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
while(true)
{
out.println(pongData);
String temp = in.readLine();
if(temp == "up")
{
System.out.println("Up you say");
}
}
//There is a little more but no point to give it all
The line String temp = in.readLine(); gives me this error when the client disconnects
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Pong.PongPlayerThread.run(PongPlayerThread.java:36)
Here is the client code
try
{
socket = new Socket(host, port);
serverOut = new PrintWriter(socket.getOutputStream(), true);
serverInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (UnknownHostException e)
{
System.err.println("Couold not connect to host:" + host);
System.exit(1);
}
catch (IOException e)
{
System.err.println("Could not get Input/Output from server");
System.exit(1);
}
System.out.println("Connected to Server");
while ((pos = serverInput.readLine()) != null)
{
String[] posValues = pos.split(":");
model.getBall().setX(Double.parseDouble(posValues[0]));
model.getBall().setY(Double.parseDouble(posValues[1]));
if(PongController.moveUp == true)
{
serverOut.println("up");
PongController.moveUp = false;
}
//If the client presses up or down arrow, a message will be sent to the server
//the server will then update the movement and the clients will be able to see it
}
This code works, but it doesn't seem to actually send the message up at all :(, If anyone could help me that would be awesome
Canvas
I have just editted some code and I have found out that in the PlayerThread the lines
if(temp.equals("up"))
{
System.out.println("Up you say");
}
is the problem, my stream on the client side is set to nothing at the start, could that be the problem? sending null?
this is the updated version
while ((pos = serverInput.readLine()) != null)
{
String[] posValues = pos.split(":");
model.getBall().setX(Double.parseDouble(posValues[0]));
model.getBall().setY(Double.parseDouble(posValues[1]));
serverOut.println("nothing");
if(PongController.moveUp == true)
{
System.out.println("Up");
serverOut.println("up");
PongController.moveUp = false;
}
else
{
serverOut.println("nothing");
}
}
but I still get the same error
Checking to see if the in.readLine is equal to anything i get this here is the code
try
{
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
System.out.println("Checking readLine value");
if(in.readLine() == null)
{
System.out.println("A ok");
}
else
{
System.out.println(":" + in.readLine());
}
while(true)
{
String temp = in.readLine();
if(temp == "up")
{
System.out.println("Up you say");
}
out.println(pongData);
}
}
catch (IOException e)
{
e.printStackTrace();
}
here is the outcome
Pong
400.0:301.0:60.0:300.0:740.0:300.0
Server started
Server was setup and will try to create a socket
Data sent
Checking readLine value
Connection reset, and then followed by lots of red lines
What else can i do?
I just tried to check on my BufferedReader like so
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
System.out.println(in.toString());
System.out.println(in.readLine());
I get java.io.BufferedReader@6262937c for the in.toString but for the readLine i get the connection reset again...
Quick update,
In my client code, if i have this
while ((pos = serverInput.readLine()) != null)
{
String[] posValues = pos.split(":");
model.getBall().setX(Double.parseDouble(posValues[0]));
model.getBall().setY(Double.parseDouble(posValues[1]));
serverOut.println("nothing"); //<---
the client will connect, get the position of the pong ball, but then it will stop recieveing data from the server and just move the ball on its own accord (update method hasnt been disabled yet). the serverOut is
serverOut = new PrintWriter(socket.getOutputStream(), true);
Upvotes: 3
Views: 7504
Reputation: 3797
Ok so I've noticed you have been asking a lot of questions about networking recently and I figured maybe you need some help with the basics. This is an extremely simple server:
package com;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer implements Runnable
{
public SimpleServer()
{
started = false;
serverSocket = null;
}
public void start()
{
if(!started)
{
started = true;
try
{
serverSocket = new ServerSocket(PORT);
running = true;
serverThread = new Thread(this);
serverThread.start();
System.out.println("Server started!\n");
}catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
}
public void stop()
{
running = false;
started = false;
if(serverThread != null)
serverThread.interrupt();
serverThread = null;
}
public void run()
{
try
{
while(running)
{
try
{
Socket client = serverSocket.accept();
System.out.println("Client Accepted!");
ClientHandler handler = new ClientHandler(client);
handler.sendMessage("Hello, SimpleClient!");
System.out.println("Sendeing client a message...");
}catch(Exception e){e.printStackTrace();}
}
}catch(Exception e){e.printStackTrace();}
}
private boolean started;
private boolean running;
private ServerSocket serverSocket;
private Thread serverThread;
private static final int PORT = 8081;
public static void main(String args[])
{
SimpleServer server = new SimpleServer();
server.start();
}
public class ClientHandler implements Runnable
{
public ClientHandler(Socket socket)
{
this.socket = socket;
try
{
writer = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
running = true;
runningThread = new Thread(this);
runningThread.start();
}catch(Exception e){e.printStackTrace(); disconnect();}
}
public void disconnect()
{
running = false;
if(runningThread != null)
runningThread.interrupt();
runningThread = null;
try
{
reader.close();
}catch(Exception e){}
reader = null;
try
{
writer.close();
}catch(Exception e){}
writer = null;
try
{
socket.close();
}catch(Exception e){}
socket = null;
}
public void sendMessage(String message)
{
if(running)
{
writer.println(message);
writer.flush();
}
}
public void run()
{
try
{
String message = "";
while((message = reader.readLine()) != null && running)
{
System.out.println("Message Recieved: " + message);
}
}catch(Exception e){e.printStackTrace(); disconnect();}
}
private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
private Thread runningThread;
private boolean running;
}
}
and now here is the client:
package com;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SimpleClient implements Runnable
{
public SimpleClient()
{
try
{
socket = new Socket("127.0.0.1", PORT);
writer = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
running = true;
runningThread = new Thread(this);
runningThread.start();
}catch(Exception e){e.printStackTrace(); disconnect();}
}
public void disconnect()
{
running = false;
if(runningThread != null)
runningThread.interrupt();
runningThread = null;
try
{
reader.close();
}catch(Exception e){}
reader = null;
try
{
writer.close();
}catch(Exception e){}
writer = null;
try
{
socket.close();
}catch(Exception e){}
socket = null;
}
public void sendMessage(String message)
{
if(running)
{
writer.println(message);
writer.flush();
}
}
public void run()
{
try
{
String message = "";
while((message = reader.readLine()) != null && running)
{
System.out.println("Message Recieved: " + message);
System.out.println("Sending a response!");
sendMessage("Hello, SimpleServer!");
}
}catch(Exception e){e.printStackTrace(); disconnect();}
}
private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
private Thread runningThread;
private boolean running;
private static final int PORT = 8081;
public static void main(String args[])
{
new SimpleClient();
}
}
In order to make a successful server in Java you need to implement a lot of Object Orientation. The server would be too complex if it had to deal with not only listening for clients but also sending and receiving messages to and from those clients. This is why I usually use a ClientHandler
class. This class handles all of the communication and is very easy to implement. The client and the server should never be in the same file because they are meant to be run separately.
This also might interest you if you aren't sure exactly how server and clients should work:
I hope this helped!
John
Upvotes: 8
Reputation: 9108
You may need to flush the output.
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html#flush()
Upvotes: 1