I am programming a chat app with sockets in Java. I have this method that gets called for as many times as there are clients connected to the server.
public class ClientInfo implements Serializable
{
public ObjectOutputStream writer;
public ObjectInputStream reader;
public String user_name;
public ClientInfo(ObjectOutputStream writer, ObjectInputStream reader, String name)
{
this.reader = reader;
this.writer = writer;
this.user_name = name;
}
}//end class
/*Client side code*/
void remove_online_user(ClientInfo client_to_remove)
{
try
{
client_to_remove.reader.close(); //this should trigger server handler in client
client_to_remove.writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}//end remove_online_users()
On the client side, I create a ClientInfo object like this
client = new ClientInfo(
new ObjectOutputStream(client_socket.getOutputStream()),
new ObjectInputStream(client_socket.getInputStream()),
user_name);
new ServerHandler(client, this);
And finally, the ServerHandler (sorry for pasting all the code, I am trying my best to condense it as much as possible)
class ServerHandler implements Runnable
{
private ClientInfo server;
private ClientBackEnd client_back_end;
public ServerHandler(ClientInfo server, ClientBackEnd client_back_end)
{
this.server = server;
this.client_back_end = client_back_end;
}//end constructor
/*method invoked by start() call in constructor, manages communication between client and server*/
public void run()
{
try
{
MessageInfo message;
while ((message = (MessageInfo) server.reader.readObject()) != null)
{
if (message.clients != null)
{
for (ClientInfo cd : message.clients)
{
if (client_back_end.listModel.contains(cd)) continue;
client_back_end.listModel.addElement(cd);
}
for (Object cd : client_back_end.listModel.toArray())
{
if (message.clients.contains(cd)) continue;
client_back_end.listModel.removeElement(cd);
}
}
else
{
System.out.println("\n" + message.message_contents);
}
}
}
catch (ClassNotFoundException | IOException e)
{
//This should trigger during the execution of remove_online_user();
client_back_end.disconnect_from_server();
}
}//end run()
My goal::
When the user stops the server, all clients must be disconnected. During remove_online_user(), closing the ObjectInputStream/ObjectOutputStream should trigger an exception in the clients server Handler. But it currently does not. What am I doing wrong?
(I apologize in advance if I did not post enough information; I don't want to flabbergast anyone with 4 entire .java files. Please let me know if more information is needed)
Closing the socket will trigger an EOFException in the peer's readObject() method.
For the same reason, your read loop is invalid. readObject() doesn't return null at end of stream.
Related
So basically im writing a client-server multiplayer game.
I have a SeverCommunicationThread that creates a gameThread if he receives a RequestForGame creates a gameThread.
When i send a RequestForGame exception is thrown java.io.StreamCorruptedException: invalid type code: 00
I assume it's because both threads try to read the same ObjectInputStream, I don't have much understanding about how it works, i just know how to use it. Could you help me understand what's the problem and how to fix it?
Thanks :)
public class ServerCommunicationThread extends Thread{
private Socket connectionSocket;
private ObjectInputStream inFromClient;
private ObjectOutputStream outToClient;
private String nickname;
private ServerModelManager model;
public ServerCommunicationThread(Socket connectionSocket,
ServerModelManager model) throws IOException {
this.connectionSocket = connectionSocket;
inFromClient = new ObjectInputStream(connectionSocket.getInputStream());
outToClient = new ObjectOutputStream(connectionSocket.getOutputStream());
this.model = model;
start();
}
public void run() {
try {
String nickname = (String) inFromClient.readObject();
if (model.exists(nickname)){
System.out.println(nickname + " already exists");
outToClient.writeObject(new MessageForClient("Please choose another nickname"));
}
else
{
System.out.println(nickname + " connected, adding to list");
model.addClient(nickname, connectionSocket,outToClient,inFromClient);
this.nickname=nickname;
}
while(true){
Object o= inFromClient.readObject();//StreamCorruptedexception
if(o instanceof RequestForGame)
{
RequestForGame r=(RequestForGame)o;
String userToPlayWith=r.getUserToPlayWith();
if(userToPlayWith.equals(nickname))
{
String message="Playing with yourself makes your palms hairy, choose another opponent";
outToClient.writeObject(message);
}
else
{
System.out.println("received request to play with "+userToPlayWith+". starting game");
ClientRepresentative client1=model.getClient(nickname);
ClientRepresentative client2=model.getClient(userToPlayWith);
ServerGameThread s=new ServerGameThread(client2,client1,client2.getInStream(),client1.getInStream(),client1.getOutStream(),client2.getOutStream());
}
}
else if(o instanceof String)
{
String s=(String) o;
if(s.equals("i want to quit"))
{
model.deleteClient(nickname);
inFromClient.close();
String q="quit";
outToClient.writeObject(q);
connectionSocket.close();
System.out.println(nickname+"has quit without exc");
}
}
}
} catch (EOFException e) {
System.out.println(nickname+" has quit");
}
catch (SocketException e)
{
System.out.println(nickname+" has quit");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public class ServerGameThread extends Thread {
private ClientRepresentative client1,client2;
private ObjectInputStream inFromClient1,inFromClient2;
private ObjectOutputStream outToClient1,outToClient2;
private Field gameField;
public ServerGameThread(ClientRepresentative client1, ClientRepresentative client2,ObjectInputStream inFromClient1,ObjectInputStream inFromClient2,ObjectOutputStream outToClient1,ObjectOutputStream outToClient2)
{
System.out.println("startin game thred");
this.client1=client1;//client 1 goes first
this.client2=client2;//client 2 started game
this.inFromClient1=inFromClient1;
this.inFromClient2=inFromClient2;
this.outToClient1=outToClient1;
this.outToClient2=outToClient2;
gameField=new Field();
System.out.println("check");
start();
}
public void run()
{
System.out.println("Starting game. players: "+client1.getNickname()+";"+client2.getNickname());
try {
outToClient1.writeObject(gameField);
outToClient2.writeObject(gameField);
while(true)
{
try {
System.out.println("listening to "+client1.getNickname());
Object o1=inFromClient1.readObject();//read move from client 1.**//StreamCorruptedexception**
while(!(o1 instanceof PlayerMove))
{
o1=inFromClient1.readObject();//read move from client 1.
}
PlayerMove move1=(PlayerMove)o1;
System.out.println("received move "+move1+" sending to "+client2.getNickname());
outToClient2.writeObject(move1);
System.out.println("listening to "+client2.getNickname());
Object o2=inFromClient2.readObject();//read move from client 1.
while(!(o2 instanceof PlayerMove))
{
o2=inFromClient2.readObject();//read move from client 1.
}
PlayerMove move2=(PlayerMove)o2;
System.out.println("received move "+move2+" sending to "+client1.getNickname());
outToClient1.writeObject(move2);
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the model.addClient method though i don't think the problem is here
public void addClient(String nickname, Socket clientSocket,ObjectOutputStream stream,ObjectInputStream inStream)
{
clients.addClient(nickname, clientSocket,stream,inStream);//add to arraylist
//send client list to all clients
String[] users=this.getAvailableClients();
ObjectOutputStream[] streams=clients.getOutStreams();
for(int i=0;i<streams.length;i++)
{
try {
streams[i].writeObject(users);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The client side proxy that sends objects to server, the methods are triggered by user actions in GUI
public class Proxy {
final int PORT = 1337;
String host;
String nickname;
private Socket clientSocket;
private ObjectOutputStream outToServer;
private ObjectInputStream inFromServer;
private ClientModelManager manager;
public Proxy(String nickname,String host,ClientModelManager manager)
{
this.nickname=nickname;
this.host=host;
this.manager=manager;
this.connect(nickname);
}
public void connect(String nick)
{
Socket clientSocket;
try {
clientSocket = new Socket(host, PORT);
System.out.println("client socket created");
outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
inFromServer=new ObjectInputStream(clientSocket.getInputStream());
outToServer.flush();
outToServer.writeObject(nick);
ClientReceiverThread t=new ClientReceiverThread(inFromServer,manager);
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void makeRequest(String user)
{
try
{
outToServer.writeObject(new RequestForGame(user));
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void quit()
{
try {
outToServer.writeObject(new String("i want to quit"));
//clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMove(PlayerMove move)
{
try {
outToServer.writeObject(move);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This problem can happen if you
construct a new ObjectInputStream or ObjectOutputStream over the same socket instead of using the same ones for the life of the socket;
use another kind of stream over the same socket as well; or,
use the object streams to read or write something that isn't an object and you get out of sync.
This can also happen if the JVM reading the serialized object does not have the correct class/jar files for the object. This usually results in a ClassNotFoundException, but if you have different jar/class versions and the serialVersionUID was not changed between versions, a StreamCorruptedException is produced. (This exception may also be possible if there is a class name conflict. e.g.: a jar containing a different class with the same full class name, though they probably also need the same serilVersionUID).
Check that the client side has the correct versions of jars and class files.
There's another possibility that I ran across where if you implement a custom deserialization routine for a class by adding this method:
private void readObject( ObjectInputStream objectInputStream ) throws IOException
then objectInputStream.defaultReadObject() must be called and called before any further reads of the input stream to properly initialise the object.
I missed this and despite the object returning without an exception being thrown it was the next read of the object stream that confusingly raised the invalid type code exception.
This link provides further information on the process: http://osdir.com/ml/java.sun.jini/2003-10/msg00204.html.
I too had this exception. It occurred because I used two threads for Server class and Client class. I used one thread for object sending and receiving thing. Then it was ok. This is easy way to solve the problem if you are not familiar with synchronized.
If ObjectInputStream is constructed only once and then just passed a reference of it to the other Thread then simply enclose the access of this object inside synchronized block to make sure that only one thread can access this object at a time.
Whenever you are reading from ObjectInputStream just access it inside the synchronized block if it is shared between multiple threads.
Sample code:(do it for all the occurrences of readObject())
...
String nickname = null;
synchronized (inFromClient) {
nickname = (String) inFromClient.readObject();
}
java.io.StreamCorruptedException: invalid type code: 00
I recently ran into this problem, not doing what OP did though. Did a quick google search and didn't find anything that was too helpful and because I think I solved it I am making a comment with my solution.
TLDR: Don't have multiple threads write to the same output stream at same time (instead take turns). Will cause issues for when client side tries to read the data. Solution is putting a lock on the writing to output.
I am doing something very similar to OP, making a multiplayer (client-server model) game. I have a thread like OP that is listening for traffic. What was happening, in my server side was that server had multiple threads that were writing to a client's stream at the same time (didn't think it was possible, game was semi turn base). Client side thread that was reading the incoming traffic was throwing this exception. To solve this I basically put a lock on the part that wrote to the client's stream (on server side) so each thread in server side would have to obtain the lock before writing to the stream.
Edited my question for clarification and code:
My goal is to pass my String data from my background thread, to my main application thread. Any help is appreciated.
Here is the code that creates the main background thread. This is located in my Server.java class
public class Server {
boolean isConnected = false;
Controller controller = new Controller();
public void startHost() {
Thread host = new Thread(() -> {
Controller controller = new Controller();
ServerSocket server = null;
try {
server = new ServerSocket(GeneralConstants.applicationPort);
} catch (BindException e2) {
System.out.println("Port Already in Use!");
} catch (IOException e) {
//do nothing
}
while (true) {
if (server == null) { break; }
try {
Socket client = server.accept();
System.out.println("Client Connected: " + isConnected);
if (!isConnected) {
controller.createClientHandler(client);
isConnected = true;
System.out.println("Client Connected: " + isConnected);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
host.setDaemon(true);
host.start();
}
Here is the code that is then called when a client is connected, located in my Controller.java class.
public synchronized void createClientHandler(Socket client) {
boolean alreadyConnected = false;
if (alreadyConnected) {
//do NOT assign multiple threads for each client
} else {
ClientHandler handleClients = new ClientHandler("client", client);
}
}
The program then creates two background threads for my client, one to manage receiving messages, and sending messages.
public ClientHandler(String name, Socket s) {
clientSocket = s;
clientName = name;
receiveThread = new Thread(this::receive);
sendThread = new Thread(this::send);
connected = clientSocket.isConnected();
receiveThread.start();
sendThread.start();
}
The thread then successfully creates the inputstream and passes the object to my controller. Which then process and grabs a string assigning it to a variable
public synchronized void handleReceivedPacket(String name, BufferedReader in) {
try {
data = in.readLine();
System.out.println("Successfully assigned data to: " + data);
} catch (IOException e) {
System.out.println("Unable to read result data");
}
}
How do I access my String data from the main thread without getting null?
Aka I can call (or something similar)
controller.returnData();
from my main application. From which it'll either return null (no data yet), or actually return my data. Right now, it's always null.
Edit, this is what's actually calling controller.returnData() {
I don't want to paste a massive amount of code for fear of reaching StackOverflow's code limit, so here's my application structure.
My JavaFX creates the scene, and creates a root gridpane, it then calls a method that creates sub gridpanes based the specified input. Aka, a user can press "Main Menu" that calls my method setScene() which removes the current "sub-root" gridpane and creates a "new" scene. Right now, I have a GameBoard.java class which on button press, calls controller.returnData()
PassOption.setOnAction(event -> {
System.out.println(controller.returnData());
});
There is no functional purpose for this besides testing. If I can receive the data, then I can expand on this using the data.
Start thinking about design. In network applications you typically have to manage the following responsibilites:
Connected clients and their state (connection state, heartbeats, ...)
Received messages from the clients
Messages to transmit to the clients
It makes sense to separate those responsibilities in order to keep the code clean, readable and maintainable.
Separation can mean both, thread-wise and class-wise.
For example, you could implement it as follows:
The class ClientAcceptor is responsible for opening the socket and accepting clients. As soon as a client has connected, it delegates the further work to a controller and then waits for other clients:
public class ClientAcceptor implements Runnable {
#Override
public void run() {
while (true) {
ServerSocket server;
try {
server = new ServerSocket(1992);
Socket client = server.accept();
if (client.isConnected()) {
controller.createClientHandler(client);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The controller could then create a handler (if the controller decides to do so, e.g. it could also decline the client). The ClientHandler class could look as follows:
public class ClientHandler {
private Thread receiveThread;
private Thread sendThread;
private boolean connected;
private Socket clientSocket;
private String clientName;
private LinkedBlockingDeque<byte[]> sendQueue;
public ClientHandler(String name, Socket s) {
clientSocket = s;
clientName = name;
receiveThread = new Thread(() -> receive());
sendThread = new Thread(() -> send());
connected = clientSocket.isConnected();
receiveThread.start();
sendThread.start();
}
private void receive() {
BufferedInputStream in = null;
try {
in = new BufferedInputStream(clientSocket.getInputStream());
} catch (IOException e) {
connected = false;
}
while (connected) {
try {
byte[] bytes = in.readAllBytes();
if (bytes != null && bytes.length > 0) {
controller.handleReceivedPacket(clientName, bytes);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void send() {
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(clientSocket.getOutputStream());
} catch (IOException e) {
connected = false;
}
while (connected) {
byte[] toSend = sendQueue.getFirst();
if (toSend != null && toSend.length > 0) {
try {
out.write(toSend);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void send(byte[] packet) {
sendQueue.add(packet);
}
public void close() {
connected = false;
}
}
The ClientHandler is responsible for receiving and transmitting data. If a packet arrives it informes the controller, which parses the packet. The ClientHandler also provides a public API to send data (which is stored in a queue and handled by a thread) and close the connection.
The above code examples are neither tested, nor complete. Take it as a starting point.
I wanted to create a simple game with a server and more than one clients. Server will have several Hashmaps and Arraylists. Server will broadcast these to clients, then one by one a client may modify these and send back to server and then server will broadcast updated values to all clients.
To get started, I have created Server - Client chat app. When a client sends String message to server, Server will add that String message to it's Arraylist and will broadcast that arraylist to all clients. I have used threads so that multiple clients can send messages concurrently, but I haven't applied thread-safety yet.
Lets come to the problem. for the first time when a client sends String to server, server prints it well, add to it's arraylist, then broadcasts it to all clients and all clients can see that too. But next time when client sends String message, server accepts it, adds to arraylist and broadcasts it, but this time all clients gets old arraylist ( list with only one String which was added first ). I have printed arraylist before broadcasting and it shows modified values, but at client side it shows list with one entry only.
Part of Server code
public class ServerGUI extends javax.swing.JFrame {
public static final int SERVER_PORT = 4000;
private ServerSocket ss;
ArrayList<String> al;
ArrayList<ClientHandler> clients;
public ServerGUI() {
initComponents();
setVisible(true);
al = new ArrayList<>();
clients = new ArrayList<>();
initNet();
}
private void initNet() {
Socket ds = null;
try {
ss = new ServerSocket(SERVER_PORT, 1);
while (true) {
ds = ss.accept();
clients.add(new ClientHandler(ds));
}
} catch (Exception e) {
System.out.println("shutting down server......");
}
}
class ClientHandler extends Thread {
private Socket ds;
private ObjectOutputStream out;
private ObjectInputStream in;
public ClientHandler(Socket ds) throws Exception {
this.ds = ds;
out = new ObjectOutputStream(ds.getOutputStream());
in = new ObjectInputStream(ds.getInputStream());
start();
}
public ObjectOutputStream getOut() {
return out;
}
public void run() {
try {
while (true) {
acceptData(in);
broadcastData();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Finally called. socket closed");
if (ds != null) {
try {
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
private void acceptData(ObjectInputStream in) throws Exception {
System.out.println("acceptData called by " + Thread.currentThread().getName());
String s = (String) in.readObject();
al.add(s);
jta.setText(al.toString());
}
private void broadcastData() throws Exception {
System.out.println("broadcast called by " + Thread.currentThread().getName());
System.out.println("al is : \n" + al);
for (ClientHandler clnt : clients) {
clnt.getOut().writeObject(al);
clnt.getOut().flush();
}
}
Part of Client code
public class ClientGUI extends javax.swing.JFrame {
public static final int SERVER_PORT = 4000;
public static final String SERVER_IP = "127.0.0.1";
private Socket s1;
private ObjectOutputStream out;
private ObjectInputStream in;
private ArrayList<String> al;
public ClientGUI() {
initComponents();
setVisible(true);
initNet();
}
private void initNet() {
try {
s1 = new Socket(SERVER_IP, SERVER_PORT);
out = new ObjectOutputStream(s1.getOutputStream());
in = new ObjectInputStream(s1.getInputStream());
System.out.println("connected to server");
new ReadData();
} catch (Exception e) {
e.printStackTrace();
}
}
class ReadData extends Thread {
public ReadData() {
start();
}
public void run() {
System.out.println("client thread started");
try {
while (true) {
al = (ArrayList<String>) in.readObject();
System.out.println("client read completed, al is "+al);
jta.setText(al.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void textFieldActionPerformed(java.awt.event.ActionEvent evt) {
try {
out.writeObject(jtf.getText());
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
This is normal behavior. If you send the same object (your ArrayList) several times to a given ObjectOutputStream, the stream will send the full object the first time, and will only send a reference to this object the next times. This is what allows sending a graph of objects without consuming too much bandwidth, and without going into infinite loops because a references b which also references a.
To make sure the ArrayList is sent a second time, you need to call reset() on the ObjectOutputStream.
This question already has answers here:
Do Java sockets support full duplex?
(2 answers)
Closed 5 months ago.
I have a Java application which is Voip. I am using the one socket to send and receive information at the same time via threads. Code is shown below ..
Socket clientSocket = sockList.accept();
OutputStream outSock = clientSocket.getOutputStream();
InputStream inSock = clientSocket.getInputStream();
new Thread( new Capture(outSock)).start();
new Thread( new PlayAudio(inSock)).start();
outSock.close();
clientSocket.close();
The problem that I'm finding is that when I write to the outputstream, it blocks on the first write. I'm sending not many bytes. Bellow is my write code.
private class Capture implements Runnable{
private OutputStream out;
public Capture(OutputStream out){
this.out = out;
}
#Override
public void run() {
try{
int numBytesRead;
TargetDataLine outLine = getMic();
outLine.open();
outLine.start();
byte[] data = new byte[outLine.getBufferSize() / 5];
byte[] test = {0x1,0x1,0x1};
while(true) {
//numBytesRead = outLine.read(data, 0, data.length);
//System.out.println(numBytesRead);
out.write(test, 0, test.length);
out.flush();
/*if(numBytesRead > 0){
out.write(data, 0, data.length);
System.out.println("C");
}*/
}
}catch(Exception ex){}
}
}
The other thread that reads the sound code is ...
private class PlayAudio implements Runnable{
private InputStream in;
public PlayAudio(InputStream in){
this.in = in;
}
#Override
public void run() {
int write;
try{
SourceDataLine inLine = getSpeaker();
inLine.open();
inLine.start();
byte[] data = new byte[inLine.getBufferSize()];
byte[] test = new byte[3];
while(true){
System.out.println(1);
//write = in.read(data, 0, data.length);
in.read(test, 0 , test.length);
System.out.println(2);
/*if(write > 0){
inLine.write(data, 0, write);
System.out.println(3);
System.out.println(write);
}*/
}
} catch(Exception ex){}
}
}
I've commented a good portion of the actual code since I'm just trying to get it to work. My write function blocks indefinitely on the first write. Is it possible this could be a problem with my threads? My only thought is that the output and input streams are sharing my socket object which may cause a deadlock or something. Please let me know whats up.
Yes you can write to a sockets input and output stream at the same time.
from do-java-sockets-support-full-duplex
Since the input stream and the output stream are separate objects within the Socket, the only thing you might concern yourself with is, what happens if you had 2 threads trying to read or write (two threads, same input/output stream) at the same time? The read/write methods of the InputStream/OutputStream classes are not synchronized. It is possible, however, that if you're using a sub-class of InputStream/OutputStream, that the reading/writing methods you're calling are synchronized. You can check the javadoc for whatever class/methods you're calling, and find that out pretty quick.
Yes you can write on socket while reading , but you have to read socket in an independent thread. I am using this concept. Here the example is (read carefully it supports mutiple client as well ) :
public class TeacherServerSocket {
private Logger logger = Logger.getLogger(TeacherServerSocket.class);
public static Map<String, TeacherServerThread> connectedTeacher = new HashMap<String, TeacherServerThread>();
ServerSocket serverSocket;;
#Override
public void run() {
// starting teacher server socket
this.serverSocket = startServer();
// if unable to to start then serverSocket would have null value
if (null != this.serverSocket) {
while (true) {
//listening to client for infinite time
Socket socket = listenToClient();
if (null != socket) {
TeacherServerThread teacherServerThread = new TeacherServerThread(socket);
Thread thread = new Thread(teacherServerThread);
thread.start();
//putting teacher ip address and teacher object into map
connectedTeacher.put(teacherServerThread.getTeacherIp(),teacherServerThread);
System.out.println("INFO: Teacher is connected with address "+ teacherServerThread.getTeacherIp());
}
}
}
}
#Override
public ServerSocket startServer() {
//port number on which teacher server will be run.
int port=12345;
try {
// throw an exception if unable to bind at given port
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Teacher server socket started on port no :"+port);
return serverSocket;
} catch (IOException e) {
logger.error("Unable to start Teacher Server socket");
e.printStackTrace();
}
return null;
}
#Override
public Socket listenToClient() {
if (this.serverSocket != null) {
try {
// throw an exception is unable to open socket
Socket socket = this.serverSocket.accept();
return socket;
} catch (IOException e) {
logger.error("Unable to open socket for teacher");
e.printStackTrace();
}
}
else {
logger.error("TeacherServerSocket has got null value please restart the server");
}
return null;
}
#Override
public Map getConnectedDevicesMap() {
return TeacherServerSocket.connectedTeacher;
}
/**
* This method will send message to connected teacher which comes form student
* #author rajeev
* #param message, which comes form student
* #return void
* * */
#Override
public void publishMessageToClient(String message) {
if(TeacherServerSocket.connectedTeacher.size()>0){
System.out.println("Total Connected Teacher: "+TeacherServerSocket.connectedTeacher.size());
for (String teacherIp : TeacherServerSocket.connectedTeacher.keySet()) {
TeacherServerThread teacherServerThread=TeacherServerSocket.connectedTeacher.get(teacherIp);
teacherServerThread.publishMessageToTeacher(message);
}
}
}
#Override
public void stopServer() {
if (this.serverSocket != null) {
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
To read in an in independent thread for multiple client :
public class TeacherServerThread implements Runnable {
Logger logger=Logger.getLogger(TeacherServerThread.class);
Socket socket;
String teacherIp;
public TeacherServerThread(Socket socket) {
this.socket=socket;
this.teacherIp=socket.getInetAddress().toString();
}
#Override
public void run() {
//starting reading
ReadFromTeacherAndPublishToStudent messageReader=new ReadFromTeacherAndPublishToStudent();
Thread thread=new Thread(messageReader);
thread.start();
}
private class ReadFromTeacherAndPublishToStudent implements Runnable {
#Override
public void run() {
String message=null;
try {
BufferedReader readTeacherData=new BufferedReader(new InputStreamReader(socket.getInputStream()));
StudentServerSocket studentServerSocket=new StudentServerSocket();
//sending message to student which is read by teacher
while((message=readTeacherData.readLine())!=null){
//System.out.println("Message found : "+message);
// studentServerSocket.publishMessageToClient(message); // do more stuff here
}
// if message has null value then it mean socket is disconnected.
System.out.println("INFO: Teacher with IP address : "+teacherIp+" is disconnected");
TeacherServerScoket.connectedTeacher.remove(getTeacherIp());
if(null!=socket){
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} //class
public void publishMessageToTeacher(String message){
if(this.socket!=null){
try {
PrintWriter writeMessageToTeacher=new PrintWriter(this.socket.getOutputStream());
writeMessageToTeacher.println(message);
writeMessageToTeacher.flush();
System.out.println(" Message published to teacher"+message);
}catch(Exception e){
logger.error(e.toString());
logger.error("Exception In writing data to teacher");
}
}else {
logger.error("Unable to publish message to teacher .Socket has Null value in publishMessageToTeacher");
System.out.println("ERROR: socket has null value can not publish to teacher");
}
}
public String getTeacherIp()
{
return teacherIp;
}
}
change code according to you requirement......
The reason it seems my write() is blocking is because I stupidly closed the Socket() and my input streams didn't realize it. Hence, no data is ever sent out. Silly error on my behalf.
So basically im writing a client-server multiplayer game.
I have a SeverCommunicationThread that creates a gameThread if he receives a RequestForGame creates a gameThread.
When i send a RequestForGame exception is thrown java.io.StreamCorruptedException: invalid type code: 00
I assume it's because both threads try to read the same ObjectInputStream, I don't have much understanding about how it works, i just know how to use it. Could you help me understand what's the problem and how to fix it?
Thanks :)
public class ServerCommunicationThread extends Thread{
private Socket connectionSocket;
private ObjectInputStream inFromClient;
private ObjectOutputStream outToClient;
private String nickname;
private ServerModelManager model;
public ServerCommunicationThread(Socket connectionSocket,
ServerModelManager model) throws IOException {
this.connectionSocket = connectionSocket;
inFromClient = new ObjectInputStream(connectionSocket.getInputStream());
outToClient = new ObjectOutputStream(connectionSocket.getOutputStream());
this.model = model;
start();
}
public void run() {
try {
String nickname = (String) inFromClient.readObject();
if (model.exists(nickname)){
System.out.println(nickname + " already exists");
outToClient.writeObject(new MessageForClient("Please choose another nickname"));
}
else
{
System.out.println(nickname + " connected, adding to list");
model.addClient(nickname, connectionSocket,outToClient,inFromClient);
this.nickname=nickname;
}
while(true){
Object o= inFromClient.readObject();//StreamCorruptedexception
if(o instanceof RequestForGame)
{
RequestForGame r=(RequestForGame)o;
String userToPlayWith=r.getUserToPlayWith();
if(userToPlayWith.equals(nickname))
{
String message="Playing with yourself makes your palms hairy, choose another opponent";
outToClient.writeObject(message);
}
else
{
System.out.println("received request to play with "+userToPlayWith+". starting game");
ClientRepresentative client1=model.getClient(nickname);
ClientRepresentative client2=model.getClient(userToPlayWith);
ServerGameThread s=new ServerGameThread(client2,client1,client2.getInStream(),client1.getInStream(),client1.getOutStream(),client2.getOutStream());
}
}
else if(o instanceof String)
{
String s=(String) o;
if(s.equals("i want to quit"))
{
model.deleteClient(nickname);
inFromClient.close();
String q="quit";
outToClient.writeObject(q);
connectionSocket.close();
System.out.println(nickname+"has quit without exc");
}
}
}
} catch (EOFException e) {
System.out.println(nickname+" has quit");
}
catch (SocketException e)
{
System.out.println(nickname+" has quit");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public class ServerGameThread extends Thread {
private ClientRepresentative client1,client2;
private ObjectInputStream inFromClient1,inFromClient2;
private ObjectOutputStream outToClient1,outToClient2;
private Field gameField;
public ServerGameThread(ClientRepresentative client1, ClientRepresentative client2,ObjectInputStream inFromClient1,ObjectInputStream inFromClient2,ObjectOutputStream outToClient1,ObjectOutputStream outToClient2)
{
System.out.println("startin game thred");
this.client1=client1;//client 1 goes first
this.client2=client2;//client 2 started game
this.inFromClient1=inFromClient1;
this.inFromClient2=inFromClient2;
this.outToClient1=outToClient1;
this.outToClient2=outToClient2;
gameField=new Field();
System.out.println("check");
start();
}
public void run()
{
System.out.println("Starting game. players: "+client1.getNickname()+";"+client2.getNickname());
try {
outToClient1.writeObject(gameField);
outToClient2.writeObject(gameField);
while(true)
{
try {
System.out.println("listening to "+client1.getNickname());
Object o1=inFromClient1.readObject();//read move from client 1.**//StreamCorruptedexception**
while(!(o1 instanceof PlayerMove))
{
o1=inFromClient1.readObject();//read move from client 1.
}
PlayerMove move1=(PlayerMove)o1;
System.out.println("received move "+move1+" sending to "+client2.getNickname());
outToClient2.writeObject(move1);
System.out.println("listening to "+client2.getNickname());
Object o2=inFromClient2.readObject();//read move from client 1.
while(!(o2 instanceof PlayerMove))
{
o2=inFromClient2.readObject();//read move from client 1.
}
PlayerMove move2=(PlayerMove)o2;
System.out.println("received move "+move2+" sending to "+client1.getNickname());
outToClient1.writeObject(move2);
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the model.addClient method though i don't think the problem is here
public void addClient(String nickname, Socket clientSocket,ObjectOutputStream stream,ObjectInputStream inStream)
{
clients.addClient(nickname, clientSocket,stream,inStream);//add to arraylist
//send client list to all clients
String[] users=this.getAvailableClients();
ObjectOutputStream[] streams=clients.getOutStreams();
for(int i=0;i<streams.length;i++)
{
try {
streams[i].writeObject(users);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The client side proxy that sends objects to server, the methods are triggered by user actions in GUI
public class Proxy {
final int PORT = 1337;
String host;
String nickname;
private Socket clientSocket;
private ObjectOutputStream outToServer;
private ObjectInputStream inFromServer;
private ClientModelManager manager;
public Proxy(String nickname,String host,ClientModelManager manager)
{
this.nickname=nickname;
this.host=host;
this.manager=manager;
this.connect(nickname);
}
public void connect(String nick)
{
Socket clientSocket;
try {
clientSocket = new Socket(host, PORT);
System.out.println("client socket created");
outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
inFromServer=new ObjectInputStream(clientSocket.getInputStream());
outToServer.flush();
outToServer.writeObject(nick);
ClientReceiverThread t=new ClientReceiverThread(inFromServer,manager);
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void makeRequest(String user)
{
try
{
outToServer.writeObject(new RequestForGame(user));
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void quit()
{
try {
outToServer.writeObject(new String("i want to quit"));
//clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMove(PlayerMove move)
{
try {
outToServer.writeObject(move);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This problem can happen if you
construct a new ObjectInputStream or ObjectOutputStream over the same socket instead of using the same ones for the life of the socket;
use another kind of stream over the same socket as well; or,
use the object streams to read or write something that isn't an object and you get out of sync.
This can also happen if the JVM reading the serialized object does not have the correct class/jar files for the object. This usually results in a ClassNotFoundException, but if you have different jar/class versions and the serialVersionUID was not changed between versions, a StreamCorruptedException is produced. (This exception may also be possible if there is a class name conflict. e.g.: a jar containing a different class with the same full class name, though they probably also need the same serilVersionUID).
Check that the client side has the correct versions of jars and class files.
There's another possibility that I ran across where if you implement a custom deserialization routine for a class by adding this method:
private void readObject( ObjectInputStream objectInputStream ) throws IOException
then objectInputStream.defaultReadObject() must be called and called before any further reads of the input stream to properly initialise the object.
I missed this and despite the object returning without an exception being thrown it was the next read of the object stream that confusingly raised the invalid type code exception.
This link provides further information on the process: http://osdir.com/ml/java.sun.jini/2003-10/msg00204.html.
I too had this exception. It occurred because I used two threads for Server class and Client class. I used one thread for object sending and receiving thing. Then it was ok. This is easy way to solve the problem if you are not familiar with synchronized.
If ObjectInputStream is constructed only once and then just passed a reference of it to the other Thread then simply enclose the access of this object inside synchronized block to make sure that only one thread can access this object at a time.
Whenever you are reading from ObjectInputStream just access it inside the synchronized block if it is shared between multiple threads.
Sample code:(do it for all the occurrences of readObject())
...
String nickname = null;
synchronized (inFromClient) {
nickname = (String) inFromClient.readObject();
}
java.io.StreamCorruptedException: invalid type code: 00
I recently ran into this problem, not doing what OP did though. Did a quick google search and didn't find anything that was too helpful and because I think I solved it I am making a comment with my solution.
TLDR: Don't have multiple threads write to the same output stream at same time (instead take turns). Will cause issues for when client side tries to read the data. Solution is putting a lock on the writing to output.
I am doing something very similar to OP, making a multiplayer (client-server model) game. I have a thread like OP that is listening for traffic. What was happening, in my server side was that server had multiple threads that were writing to a client's stream at the same time (didn't think it was possible, game was semi turn base). Client side thread that was reading the incoming traffic was throwing this exception. To solve this I basically put a lock on the part that wrote to the client's stream (on server side) so each thread in server side would have to obtain the lock before writing to the stream.