On the server, when I get a new connection (serverSocket.accept()),
I pass that connection socket to an instance of a class called ServerPlayer.java,
which extends from a thread.
I also create an OutputObjectStream and an InputObjectStream and pass those to the new ServerPlayer instance, and then add the ServerPlayer instance to an ArrayList to keep track of them.
When I call start() on the new ServerPlayer, I have it write a byte (1).
I then have my client run a Listening thread which listens for incoming data from the TCP Server. However, I am not receiving the (1) I sent from the server. I'm not sure if the Server just isn't sending it properly or if the client isn't receiving it properly...
ServerPlayer.java:
/**
* ServerPlayer.java
* Creates a new instance of a player on the server, gives it
* an output and input stream, as well as the socket it came in on
*/
package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerPlayer extends Thread {
UIServer ui;
Socket socket;
ObjectOutputStream os;
ObjectInputStream is;
int id = -1;
ServerPlayer(Socket socket, ObjectOutputStream os, ObjectInputStream is, UIServer ui){
this.socket = socket;
this.os = os;
this.is = is;
this.ui = ui;
}
public void setID(int id){
this.id = id;
}
public int getID(){
return this.id;
}
public void run(){
boolean keepGoing = true;
System.out.println("SERVERPLAYER THREAD START");
try {
os.writeByte(1);
System.out.println("sent byte 1 from server");
} catch (IOException ex) {
Logger.getLogger(ServerPlayer.class.getName()).log(Level.SEVERE, null, ex);
}
while(keepGoing){
try{
Byte msg = is.readByte();
int mes_id = msg.intValue();
ui.console.println("SERV MESSAGE#: " + mes_id);
} catch (IOException ex) {
Logger.getLogger(ServerPlayer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
ListenFromServer.Java:
/*
* ListenFromServer.java
* Listens for incoming data from the TCP Server (this is on the client side)
*/
package client;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ListenFromServer extends Thread {
TCPClient client;
boolean isRunning = false;
public ListenFromServer(TCPClient client){
this.client = client;
}
public void run(){
System.out.println("listen from server thread start");
isRunning = true;
while(isRunning){
try {
Byte b = client.sInput.readByte();
client.ui.console.println("BYTE: " + b.intValue());
} catch (IOException ex) {
Logger.getLogger(ListenFromServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
run()method of the thread. Otherwise you can block other parts of your program. And create theObjectOutputStreambefore theObjectInputStream.- user207421