Java, problem sending a message with socket connection - java

I have a problem with my Java program. It has a socket connection between a server and many client. Here is the server (the part which concerns the problem):
private static ArrayList<ParallelServer> clientConnected = new ArrayList<ParallelServer>();
public Server(int port) {
this.port = port;
if (!startServer())
JOptionPane.showMessageDialog(new JFrame(""),
"Error!", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
private boolean startServer() {
try {
server = new ServerSocket(port);
loadDatabase();
} catch (IOException ex) {
ex.printStackTrace();
return false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return true;
}
public void runServer() {
while (true) {
try {
client = server.accept();
ParallelServer pServer = new ParallelServer(client);
clientConnected.add(pServer);
Thread thread = new Thread(pServer);
thread.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void sendBroadcast(String username) throws IOException {
for(int i = 0; i < clientConnected.size(); i++)
clientConnected.get(i).sendAnswer("#change," + username);
}
The parallel server is:
private Socket client;
private InputStreamReader inputstreamreader;
private BufferedReader bufferedreader;
private PrintWriter printwriter;
public ParallelServer(Socket client) {
this.client = client;
}
public void run() {
try {
inputstreamreader = new InputStreamReader(client.getInputStream());
bufferedreader = new BufferedReader(inputstreamreader);
printwriter = new PrintWriter(client.getOutputStream(), true);
String lineread = "";
while (client.isConnected()) {
lineread = bufferedreader.readLine();
doCommand(lineread);
}
} catch (UnknownHostException unhe) {
} catch (InterruptedIOException intioe) {
} catch (IOException ioe) {
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void sendAnswer(String answer) throws IOException {
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.println(answer);
printwriter.flush();
}
And here is the client:
private String serverurl = "localhost";
private int serverport = 7777;
private PrintWriter printwriter;
private InputStreamReader inputstreamreader;
private BufferedReader bufferedreader;
private Socket server;
public Client() {
server = null;
try {
server = new Socket(serverurl, serverport);
server.setSoTimeout(5000);
} catch (UnknownHostException unhe) {
System.out.println("UnknownHostException: " + unhe.getMessage());
} catch (InterruptedIOException intioe) {
System.out.println("Timeout while attempting to establish socket connection.");
} catch (IOException ioe) {
JOptionPane.showMessageDialog(new JFrame(),"Unable to reach the server!","ERROE!",JOptionPane.ERROR_MESSAGE);
}
}
public String sendCommand(String command) throws IOException {
if(server == null) {
try {
server = new Socket(serverurl, serverport);
server.setSoTimeout(5000);
} catch (UnknownHostException unhe) {
System.out.println("UnknownHostException: " + unhe.getMessage());
} catch (InterruptedIOException intioe) {
System.out.println("Timeout while attempting to establish socket connection.");
} catch (IOException ioe) {
JOptionPane.showMessageDialog(new JFrame(),"Unable to reach the server!","ERROR!",JOptionPane.ERROR_MESSAGE);
}
}
if(server != null) {
printwriter = new PrintWriter(server.getOutputStream(), true);
printwriter.println(command);
printwriter.flush();
inputstreamreader = new InputStreamReader(server.getInputStream());
bufferedreader = new BufferedReader(inputstreamreader);
return bufferedreader.readLine();
}
else
return "#serverProblem";
}
The program is a simple online game with turns. Players' turns are created with a queue and when a player passes his turn, the server send a broadcast message which say "Now it is 'Player 1' turn." (for instance). My problem is that when a client receive the message, its like it add the answer "Now it is 'Player 1' turn." to the next message it will receive. In my case: when a player passes his turn, he sends "#passTurn,username". The ParallelServer class polls it from the queue, puts it at the bottom of the queue, sends the client "#ok" to tell it that the turn has changed successfully and tells the Server class to send the broadcast message. Then, when the same client will try do do a further action, it will consider "Now it is 'Player 1' turn." as the answer the server has given to it. Instead, I would like that the server and the clients work as always and when the broadcast message is cought, the client is notified without any collateral effect.
What can I do?
Thanks.

Your bi-directional message passing mechanism should look something like this:
Server:
Wait on any client InputStream
if (broadcast)
broadcast_message()
else
process_message()
Client:
Receiving Thread:
Wait on server broadcast
Sending Thread:
Wait on messages to be sent to server from the User Input
This should do the trick :)
Hope it helps. Cheers!

Related

client creates new socket object everytime the server is on

i've done a socket programming with client residing on android and server residing on the desktop ....... whenever server is down as we know client lost the connection.....so it undergoes a looping until it connects to server.......
here the problem is in the below code
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
in the while loop in the case of lost connection.........but when the connection is on it again creates a new object........
can anyone please tell me how to solve this problem..........
In the client side
while(true){
try {
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
tabletout = new PrintWriter(tabletclient.getOutputStream());
in = new Scanner(tabletclient.getInputStream());
try
{
if((line = in.nextLine())!=null)
{
// my task to be done
}
}catch(Exception d){
System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"+tabletclient.isConnected());
}
} catch (UnknownHostException e) { System.out.println("Entered 2.........");
} catch (IOException e) { System.out.println("Entered 3.........");e.printStackTrace();
}
}
In in the Server side
:
:
private Set <Socket> TABhs=new HashSet<Socket>();
:
:
new Thread(new TABServerThread()).start(); // runs in background
:
:
:
class ServerThread implements Runnable {
private ServerSocket server;
#Override
public void run() {
try {
server = new ServerSocket(SERVER_PORT);
System.out.println("Server Start the server at port " + SERVER_PORT
+ " and waiting for clients...");
while (true) {
Socket socket = server.accept();
System.out.println("Server Accept socket connection: "
+ socket.getLocalAddress());
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static PrintWriter out;
class ClientHandler implements Runnable {
private Socket clientSocket;
private Scanner in;
public ClientHandler(Socket clietSocket) {
this.clientSocket = clietSocket;
}
#Override
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream());
in = new Scanner(clientSocket.getInputStream());
String line;
System.out.println("ClientHandlerThread Start communication with : "+ clientSocket.getLocalAddress());
try{
while((line = in.nextLine()) != null) {
System.out.println("ClientHandlerThread Client says: " + line);
String dat[]=line.split("#");
String query="insert into table_orders (tableno,kotno, orders,status) values('"+dat[1]+"','"+dat[0]+"','"+dat[2]+"','pending')";
try {
int i= dbGetDet.insertDetails(query);
if(i>0)
{
fillTable();
filtercomboBox();
out.print("success");
out.flush();
for(Socket so:TABhs)
{
PrintWriter ot = new PrintWriter(so.getOutputStream());
ot.println("tableallocation#"+dat[1]);
ot.flush();
}
System.out.println("SENDED 'SUCCESS' TO CLIENT");
}
} catch (Exception ex) {
Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
}
// }
}
}catch(Exception r){}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the Button click of server
String stat=status_combo.getSelectedItem().toString();
String tables=tableno_combo.getSelectedItem().toString();
String kotno=kotno_combo.getSelectedItem().toString();
if(stat.equals("Processing"))
{
try {
TABhs = new CopyOnWriteArraySet(TABhs);
int soint=1;
System.out.println("TABhs Processing--------------------->"+TABhs.size());
for(Iterator <Socket> it=TABhs.iterator();it.hasNext();)
{
Socket so=it.next();
System.out.println("SEEE SOCKET Processing"+soint+"----->"+so.isClosed());
PrintWriter ot = new PrintWriter(so.getOutputStream());
ot.println("tableupdate#"+tables+"#"+kotno+"#processing");
ot.flush();
JOptionPane.showMessageDialog(rootPane, "<html><body>Table Kot Status Changed to <b>Processing</b></body></html>");
soint++;
}
System.out.println("TABhs Processing--------------------->"+TABhs.size());
}
catch (Exception ex) {
Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
}
}
NOW EACH TIME WHEN BUTTON IS CLICKED THE OUTPUT IS AS GIVEN BELOW
FISRT CLICK
SEEE SOCKET Ready 1----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 2----->false
TABhs--------------------->2
SECOND CLICK
SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 3----->false
TABhs--------------------->4
FOURTH CLICK
SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
SEEE SOCKET Ready 3----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 4----->false
TABhs--------------------->5
I think the problem is at the client's side you read a line and then create a new connection.
I think you must keep reading the socket until it's closed or an error occurs.
For example:
while (true)
{
tabletclient = null;
int loop = 0;
// loop until a connection is established
while (tabletclient == null)
{
try
{
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
}
catch (Exception e)
{
e.printStackTrace();
// set the value to quit when no connection could be established
if (loop++ > 100)
return;
}
}
try
{
tabletout = new PrintWriter(tabletclient.getOutputStream());
in = new Scanner(tabletclient.getInputStream());
// read the socket until it's closed or an error occurs
try
{
while ((line = in.nextLine()) != null)
{
// my task to be done
}
}
catch (Exception d)
{
System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"
+ tabletclient.isConnected());
}
tabletsocket.close();
}
catch (UnknownHostException e)
{
System.out.println("Entered 2.........");
}
catch (IOException e)
{
System.out.println("Entered 3.........");
e.printStackTrace();
}
}
Also, you must close the server side when the transfer from the server to the client is completed.

Need help in protocol buffer in client server using java

I am new to google protocol buffer . I am writing a client server application where client send request object to server and server return response. Currently when i send object to server neither the server respond nor throw any exception. Probably it stuck on line
Request request = Request.parseFrom(bytes);
where Request and Response are my message classes generated by protocol buffer.
My code samples are as follows
public class TCPServer {
final static Logger logger = Logger.getLogger(TCPServer.class.getName());
static int PORT = 6789;
public static void main(String argv[]) throws Exception
{
ServerSocket socket = new ServerSocket(PORT);
Socket connectionSocket = null;
while(true)
{
try{
connectionSocket = socket.accept();
}catch (IOException e) {
System.out.println("Could not listen on port:" + PORT);
System.exit(-1);
}
Thread thread = new Thread(new ServerConnection(connectionSocket));
thread.start();
}
}
}
public class ServerConnection implements Runnable{
static final Logger logger = Logger.getLogger(ServerConnection.class.getName());
String clientInput;
String serverOutput = null;
Socket connectionSocket = null;
ServerConnection(Socket connectionSocket){
this.connectionSocket = connectionSocket;
}
public void run() {
try {
InputStream input = connectionSocket.getInputStream();
ObjectInputStream inFromClient = new ObjectInputStream(input);
ObjectOutputStream outToClient = new ObjectOutputStream(connectionSocket.getOutputStream());
serveRequest(inFromClient , outToClient);
outToClient.flush();
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
System.out.println("Exception occured in ServerConnection run() method");
}
}
public void serveRequest(InputStream inFromClient, OutputStream outToClient){
try {
System.out.println("Recieving data from client");
ResponseReciever response = new ResponseReciever();
ObjectInputStream input = (ObjectInputStream) inFromClient;
byte size = input.readByte();
byte []bytes = new byte[size];
input.readFully(bytes);
Request request = Request.parseFrom(bytes);
System.out.println("Request recieved");
response.createResponse(request.getId(),request.getMessage(),true).writeTo(outToClient);
System.out.println("Response send");
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
System.out.println("Exception occured in ServerConnection serverRequest() method");
}
}
And my client look like this
public class TCPClient {
final static Logger logger = Logger.getLogger(TCPClient.class.getName());
private static int PORT = 6789;
private static String HOST_NAME = "localhost";
private static boolean isOpen = true;
private Socket openConnection(final String hostName,final int port){
Socket clientSocket = null;
try {
clientSocket = new Socket(HOST_NAME, PORT);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception occured while connecting to server", e);
}
return clientSocket;
}
private void closeConnection(Socket clientSocket){
try {
logger.log(Level.INFO, "Closing the connection");
clientSocket.close();
isOpen = false;
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception occured while closing the connection", e);
}
}
public void sendToServer(OutputStream output){
try {
System.out.println("Sending data to server");
RequestSender requestSender = new RequestSender();
Request request = requestSender.getRequest(1,"param1","param2",23L,"Its message",true);
ObjectOutputStream outputStream = (ObjectOutputStream)output;
request.writeTo(outputStream);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
public void recieveFromServer(InputStream input){
try {
System.out.println("Recieving data from server");
Response response = Response.parseFrom(input);
System.out.println(response.getId());
System.out.println(response.getResponse());
System.out.println(response.getError());
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
public static void main(String argv[]) throws Exception
{
ObjectOutputStream outToServer = null;
InputStream inFromServer = null;
TCPClient client = new TCPClient();
try {
while(isOpen)
{
Socket clientSocket = client.openConnection(HOST_NAME, PORT);
outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
inFromServer = new ObjectInputStream(clientSocket.getInputStream());
client.sendToServer(outToServer);
client.recieveFromServer(inFromServer);
}
}catch (Exception e) {
logger.log(Level.SEVERE, "Exception occured ", e);
System.out.println("Exception occured in TCPClient main() method");
System.exit(1);
}
}
}
I am unable to find what is wrong in the code. Please let me know if you find something missing.
It works by using writeDelimtedTo(outputStream) and parseDelimitedFrom(inputStream) instead of writeTo(outputStream) and parseFrom(inputStream). So by putting the following code on server and client sides the program works.
Server side:
InputStream input = connectionSocket.getInputStream();
OutputStream output = connectionSocket.getOutputStream();
Request request = null;
while ((request = Request.parseDelimitedFrom(input)) != null) {
System.out.println(request.toString());
}
Client side:
Socket clientSocket = client.openConnection(HOST_NAME, PORT);
Request request = getRequest();
OutputStream output = clientSocket.getOutputStream();
InputStream input = clientSocket.getInputStream();
request.writeDelimitedTo(output);
If you start sending protocol buffers over the wire - then you will need to "frame" them. The problem is reported and solved with this question: does protobuf need a network packet header?
Instead of writing all this code, you could checkout https://code.google.com/p/protobuf-rpc-pro/ and see if it satisfies your requirements for RPC between java server and java clients.

Using a ServerSocket without port forwarding?

This may be a stupid question, but here goes.
Im writing this chat program, where there is a server, and clients that can connect to it. I want to implement private messaging into the program, but I don't know how to get the clients to directly connect to eachother. For the server, I used a ServerSocket, which runs on a single port. To get that to work, I needed to forward a port to the server. Is there a way to get the clients to wait for connections, without forwarding a port to them?
Thanks
The whole point of TCP/IP is that a single client connects to a predefined port on a server. So yes, you'll also need to have a ServerSocket on the client that's going to accept the direct connection. You'll almost always run into trouble with port forwarding and the like, which is why UPnP was invented one day.
What you are trying to do is 'peer to peer' connectivity, aka P2P, which is always, by its very definition, plagued by firewalling problems. As such it's usually, especially for a chat, easier to use the central server as 'switchboard' server and relay the private messages as well.
I've written not long time ago a template for multiple client - server application, that might help you to solve your problem. The rest of your question was already answerd by #Niels, I think ;)
import java.net.*;
import java.io.*;
class ServeConnection extends Thread {
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
public ServeConnection(Socket s) throws IOException {
// init connection with client
socket = s;
try {
in = new BufferedReader(new InputStreamReader(
this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O.");
System.exit(1);
}
start();
}
public void run() {
System.out.println("client accepted from: " + socket.getInetAddress()
+ ":" + socket.getPort());
// get commands from client, until is he communicating or until no error
// occurs
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
System.out.println("request: " + inputLine);
outputLine = inputLine;
out.println("I've recived "+outputLine);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("server ending");
out.close();
try {
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server {
public static void svr_main(int port) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
System.out.println("Server ready");
try {
while (true) {
Socket socket = serverSocket.accept();
try {
new ServeConnection(socket);
} catch (IOException e) {
System.err.println("IO Exception");
}
}
} finally {
serverSocket.close();
}
}
}
class Client {
static Socket echoSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public static void cli_main(int port, String servername) throws
IOException {
try {
echoSocket = new Socket(servername, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + servername);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + servername);
System.exit(1);
}
System.out.println("Client ready!");
while (true) {
inputLine = (in.readLine().toString());
if (inputLine == null) {
System.out.println("Client closing!");
break;
}
// get the input and tokenize it
String[] tokens = inputLine.split(" ");
}
out.close();
in.close();
echoSocket.close();
System.out.println("Client closing");
}
}
public class MyClientServerSnippet{
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
System.err.println("Server: java snippet.MyClientServerSnippet<port>");
System.exit(1);
}
else if (args.length > 1) {
System.out.println("Starting client...\n");
Client client = new Client();
client.cli_main(3049, "127.0.0.1");
} else {
System.out.println("Starting server...\n");
Server server = new Server();
server.svr_main(3049);
}
}
}

Java Client/Server Socket Broken Pipe

I'm creating an update client via Sockets and I'm getting a Broken Pipe on the server side. The server accepts a client socket and responds to the same socket with either a message or a large byte array (~180MB). The error does not happen when testing locally (both client and server on the same machine) and it seems that it happens while sending the byte array. I'm not specifying a time out on the client socket and don't know why it is closing before reading the full response. Its my first time working with sockets and any help would be appreciated.
My Client Socket Code:
public static Response makeRequest(Request req) throws IOException {
Response response = null;
Socket echoSocket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
echoSocket = new Socket(serverHost, 10008);
out = new ObjectOutputStream(echoSocket.getOutputStream());
in = new ObjectInputStream(
echoSocket.getInputStream());
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
out.writeObject(req);
try {
response = (Response)in.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
return response;
}
Response is just a POJO holding the response (string/byte[] and other data)
My Server Code (copied an example of Sun/Oracle site and added my code to it)
public class Server extends Thread {
private Socket clientSocket;
public Server(Socket clientSocket) {
this.clientSocket = clientSocket;
start();
}
public void run()
{
{
System.out.println ("New Communication Thread Started");
try {
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
Request request = null;
try {
request = (Request)in.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UpdateDAO dao = new UpdateDAO();
ClientDAO cdao = new ClientDAO();
Update update = null;
Client client = null;
Session s = HibernateUtil.currentSession();
Transaction t = s.beginTransaction();
if (request != null) {
client = cdao.getClient(request.getClientId());
LogItem log = new LogItem();
log.setClient(client);
log.setTimestamp(new Date());
log.setAction(request.getAction());
if (request.getResponse() != null) {
update = dao.getUpdate(request.getResponse().getUpdateId());
}
TaskContext ctx = new TaskContext(request, client, update, log);
System.out.println("Action: " + request.getAction().getDescription());
Task task = TaskFactory.getTask(request.getAction());
System.out.println(task.getClass().getName());
Response response = task.perform(ctx);
out.writeObject(response);
log.setClientTaskDescription(request.getMessage());
log.setUpdate(ctx.getUpdate());
dao.save(ctx.getLog());
if (ctx.getUpdate() != null) {
dao.update(ctx.getUpdate());
}
} else {
out.writeObject(new Response("what"));
}
t.commit();
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
}
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10008);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new Server (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
}
If the client is, in fact, running out of memory:
java -Xmx512m -jar <the jar>
or
java -Xmx512m com.foo.blah.YourClass
would increase the maximum heap for the client/server. Keep in mind you may have to increase the heap for both sides of the pipe since both sides would be reading all ~180mb into memory at runtime.

Listening on multiple sockets (InputStreamReader)

I'm having a problem with a little game I'm designing in my class.
The problem is that I got two clients connected to a server. (client1 and client2) They are each running a game, which in the end, closes the window. As the game window is a JDialog, it will then, when it's closed, send a message, through a socket, to the server, telling it that it's done. I want the server to know which of the two clients were completed first. They are reporting through a PrintWriter on the sockets' OutputStream.
What I did was this:
in1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
in2 = new BufferedReader(new InputStreamReader(client2.getInputStream()));
try {
in1.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
try {
in2.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
Problem is that it waits for the first input, before it even starts listening on the second. How can I make it listen on both at the same time? Or solve my problem some other way.
Thanks!
Server connection should work like this:
Server gameServer = new Server();
ServerSocket server;
try {
server = new ServerSocket(10100);
// .. server setting should be done here
} catch (IOException e) {
System.out.println("Could not start server!");
return ;
}
while (true) {
Socket client = null;
try {
client = server.accept();
gameServer.handleConnection(client);
} catch (IOException e) {
e.printStackTrace();
}
}
In hanleConnection() you start a new thread and run the communication for this client in the created thread. Then the server can accept a new connection (in the old thread).
public class Server {
private ExecutorService executor = Executors.newCachedThreadPool();
public void handleConnection(Socket client) throws IOException {
PlayerConnection newPlayer = new PlayerConnection(this, client);
this.executor.execute(newPlayer);
}
// add methods to handle requests from PlayerConnection
}
The PlayerConnection class:
public class PlayerConnection implements Runnable {
private Server parent;
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
protected PlayerConnection(Server parent, Socket socket) throws IOException {
try {
socket.setSoTimeout(0);
socket.setKeepAlive(true);
} catch (SocketException e) {}
this.parent = parent;
this.socket = socket;
this.out = new DataOutputStream(socket.getOutputStream());;
this.in = new DataInputStream(socket.getInputStream());
}
#Override
public void run() {
while(!this.socket.isClosed()) {
try {
int nextEvent = this.in.readInt();
switch (nextEvent) {
// handle event and inform Server
}
} catch (IOException e) {}
}
try {
this.closeConnection();
} catch (IOException e) {}
}
}

Categories

Resources