I'm new to Java socket programming and I'm trying to write a program which is supposed to be run on 2 separate controllers. I have written a thread which is used as the communication class.
I have defined a flag called SFlag so that when the value of this flag is changed to 1 anywhere in my program, the corresponding controller will send a hello message to the other controller through sendPackets() function. The other controller will receive this message through ReceivePackets class and it will print the result. Here is the code:
// My UDP communication class
public class MainConn implements Runnable {
// Sockets, 1 for sending, and one for receiving
DatagramSocket socket1, socket2;
// localIP
private InetAddress localIP;
private InetAddress leaderIP;
// classes to run on separate Threads
private ReceivePackets rcvThread;
#Override
public void run() {
process();
}
public void process() {
// initialize some parameters
init1();
// Make Thread for receiving packets and update counters from all
// controller
rcvThread = new ReceivePackets();
Thread r = new Thread(rcvThread);
r.start();
sendPackets();
}
public void init1() {
try {
// create sockets
String tempString = config.get("localPort");
localPort = Integer.parseInt(tempString);
logger.info("----------here is==========" +localPort);
leaderIP = InetAddress.getByName("127.0.0.1");
logger.info("----------here is==========" +leaderIP);
socket1 = new DatagramSocket(localPort); // for sending
socket2 = new DatagramSocket(localPort + 1); // for receiving
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
}
}
//*******************************************************
public void sendPackets() {
// will be used to begin sending message type II after 3*hello
// period
while (true) {
try {
// if network not converged, send message type I, contains:
// type number (1) then
if (SFlag == 1) {
logger.info("Sending the message");
String tempString = new String("Hello");
byte[] data = tempString.getBytes();
DatagramPacket sentPacket = new DatagramPacket(data, tempString.length());
sentPacket.setAddress(leaderIP);
sentPacket.setPort(20222);
socket1.send(sentPacket);
SFlag = 0;
}
else {
logger.info("Nothinggggggggggggg");
}
Thread.sleep(5000);// wait for Hello period
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
}
class ReceivePackets implements Runnable {
#Override
public void run() {
try {
while (true) {
logger.info("---------------waiting------------------");
byte[] data = new byte[1000];
DatagramPacket receivedPacket = new DatagramPacket(data, data.length);
socket2.receive(receivedPacket);
String senderIP = receivedPacket.getAddress().getHostAddress();
String senderPort = "" + receivedPacket.getPort();
String message = new String(data, 0, receivedPacket.getLength());
logger.info(message);
System.out.println("Received Message: "+message);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
When the value of SFlag is changed to 1, it seems that the first controller is sending the message ("Sending the message" is printed), but there seems to be a problem with receiving the message on the second controller, because the received message is not printed.
What is the problem?
There are some issues with your code:
(1) Since both threads rely on SFlag for communication, make sure it is declared with the volatile keyword:
private volatile int SFlag = 0;
The volatile keyword prevents the variable from being cached, so both threads will see the same value all the time. Besides that, reading and writing operations on volatile variables are atomic.
(2) You have a hardcoded port number in this line:
sentPacket.setPort(20222);
Make sure this is the port number used by the ReceivePackets thread. Ideally we should never have magic numbers mixed with the code. So you should move that port number to a separate variable or constant.
(3) In Java you shouldn't create a String with new. For example, this is bad practice:
String tempString = new String("Hello"); // bad practice
You should do:
String tempString = "Hello";
My last piece of advice is: clean up your code. You can look at Oracle's tutorial on sending and receiving datagram packets here: https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
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.
Lately I've been messing around a lot with DatagramChannels, and have made a pretty complicated and well functioning system, to work with them on two sides of the connection.
However, i've run into a problem. While sanity-checking my connection protocol, i realised that i have a pretty big problem with running multiple channels on one port. it seems that unlike java's TCP sockets, java's udp sockets do not properly route the packets as they arrive to the appropriate channel.
more specifically, it appears that if i have two channels, on two threads, waiting for a packet, both on the same port, but connected to different outputs, the first one that was bound will be the one to get the packet, even if it arrives from the other channel's connection. the problem is that it filters it out automatically (as it should), and as a result, that packet is fully lost forever, and the second channel will just keep on waiting.
because of technical limitations, i need the server's side to run on exactly one port, which leaves me baffled as to what should i do.
am i doing something wrong? also, is this something that is fixed by using a selector? i'm a bit new to DatagramSockets and channels, as i've mostly used the tcp ones in java up until now.
i've also got some of the sanity check's test code here to verify it, it's a bit messy, but there are two timers constantly trying to receive packets from the same connection, and only one of them is receiving.
by changing which timer task runs first, i'm able to change which one gets the packets. what baffles me even more though is the fact that the first timer task is able to work with each now socket, while still not letting the "outsider channel" receive even a single packet.
public static void main(String[] args) {
runServer();
runClient();
}
public static void runClient() {
DatagramChannel channel;
try {
channel = DatagramChannel.open();
channel.bind(new InetSocketAddress("localhost", 8000));
channel.connect(new InetSocketAddress("localhost", 8001));
while(true) {
channel.write(ByteBuffer.wrap("let's see who wins".getBytes()));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static class Channel{
DatagramChannel channel;
int number;
public Channel(int number) {
try {
channel = DatagramChannel.open();
this.number = number;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static boolean outsiderLost = false;
// client on port 8000
// server on port 8001
public static void runServer() {
ByteBuffer buf = ByteBuffer.wrap(new byte[300]);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
boolean firstTime = true;
int i = 0;
Channel channel = new Channel(i);
DatagramChannel channel1 = channel.channel;
while(true) {
try {
if(firstTime) {
channel1.socket().setReuseAddress(true);
channel1.bind(new InetSocketAddress("localhost", 8001));
channel1.connect(new InetSocketAddress("localhost", 8000));
channel1.configureBlocking(true);
firstTime = false;
} else {
SocketAddress add = channel1.receive(buf);
i++;
channel = new Channel(i);
channel1 = channel.channel;
channel1.socket().setReuseAddress(true);
channel1.bind(new InetSocketAddress("localhost", 8001));
channel1.connect(add);
buf.clear();
System.out.println("channel " + channel.number + " wins");
outsiderLost = true;
}} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 500);
Timer timer2 = new Timer();
timer2.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
DatagramChannel channel1 = null;
try {
channel1 = DatagramChannel.open();
channel1.socket().setReuseAddress(true);
channel1.bind(new InetSocketAddress("localhost", 8001));
channel1.connect(new InetSocketAddress("localhost", 8000));
channel1.configureBlocking(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(!outsiderLost) {
try {
channel1.read(buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buf.clear();
System.out.println("outsider wins");
outsiderLost = true;
}
}
}, 1000);
}
}
ended up creating one reader channel that actually reads on the server, and then reroutes the packets to the different sender channels to be processed and then send a response.
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.
My research showed (see pg. 5) that the maximum amount of data that can be sent via Bluetooth 4.2 is 257 bytes.
However, I was able to send 990 bytes between my Python script and Java application. Why was I able to send so much data? Is the information I found about the maximum data wrong, or did something else happen?
Python Bluetooth script:
#Parameters config
sdr=RtlSdr()
sdr.fc=100e6
sdr.gain=48
sdr.rs=1.024e6
#Bluetooth connection
server_sock=BluetoothSocket(RFCOMM)
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port=server_sock.getsockname()[1]
uuid="94f39d29-7d6d-437d-973b-fba39e49d4ee"
client_sock,client_info=server_sock.accept()
while (1):
samples= sdr.read_samples(256*1024)
result=psd(samples, NFFT=70, Fc=sdr.fc/1e6, Fs=sdr.rs/1e6)
tab_freq=(result[1])
value_freq=str(tab_freq)[1:-1]
value_freq2=[format(float(v),".4f")[:6] for v in value_freq.split()]
value_freq3="\n".join(value_pxx2)
#SAME FOR POWER VALUE
#THEN I SEND DATA BY BLUETOOTH
client_sock.send(value_freq3)
Java Bluetooth code:
private class ThreadConnected extends Thread {
private final BluetoothSocket connectedBluetoothSocket;
private final InputStream connectedInputStream;
private final OutputStream connectedOutputStream;
boolean running;
public ThreadConnected(BluetoothSocket socket) {
connectedBluetoothSocket = socket;
InputStream in = null;
OutputStream out = null;
running = true;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connectedInputStream = in;
connectedOutputStream = out;
}
#Override
public void run() {
byte[] buffer = new byte[1048576]; // 20 bits
int bytes;
String strRx = "";
while (running) {
try {
bytes = connectedInputStream.read(buffer);
final String strReceived_freq = new String(buffer,0, bytes/2);
final String strReceived_pxx = new String(buffer,(bytes/2)+1, bytes);
//final int samples_sdr=new Integer(buffer,0,bytes);
final String strByteCnt = String.valueOf(bytes) + " bytes received.\n";
runOnUiThread(new Runnable(){
#Override
public void run() {
Pxx_value.setText(strReceived_pxx+"\n"); // get data PXX
freq_value.setText(strReceived_freq+"\n"); // get data freq
// plot value
/* for (int i=0; i<nb_points; i++)
{
freq[i]=Double.parseDouble(strReceived_freq);
pxx[i]=Double.parseDouble(strReceived_pxx);
series.appendData(new DataPoint(freq[i],pxx[i]), true,500);
}*/
}});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
cancel();
final String msgConnectionLost = "Connection lost:\n" + e.getMessage();
runOnUiThread(new Runnable(){
#Override
public void run() {
}});
}
}
}
public void write(byte[] buffer) {
try {
connectedOutputStream.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void cancel() {
running = false;
try {
connectedBluetoothSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The document you link to shows the LE (low energy) Link Layer packet format, as specified in Vol 6, Part B, Section 2.1 of the Bluetooth Core Specification.
You are using RFCOMM, which is a Bluetooth Classic (aka BR/EDR) profile. The Link Layer packet format for BR/EDR is specified in Vol 2, Part B, Section 6 and shows that the payload can be up to 2790 bytes long.
In any case the API you are using doesn't give you access to the Link Layer. You are writing on an RFCOMM channel (which is designed to work more or less like a serial port) and you can write as many bytes as you want. Your library and the underlying platform will take care of placing your data into the appropriate number of L2CAP packets, which will then be further encapsulated in link layer packets. The main limitation you will run into are the buffer sizes in your implementation. In this case your socket based API will return the number of bytes that were written in the call to send, and you will be able to attempt retransmission later.
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.