Java Socket Programming MultiPlayer Kart Racing Game Shows Blank Screen - java

Basically I am developing a multiplayer kart racing game using TCP. There will be two clients and one server. The clients connected will be passed as a thread running. The first connected client will be assigned as player 1 and the later to be player 2.
The protocol that I have developed is:
Player 1 sends its kart's information to server and server forwards it to Player 2.
Player 2 then sends its kart's information to server and server forwards it to Player 1.
I am sending String like "KART1:X:200" over the network. However, when entire project runs, the two clients are successfully connected, but the jFrame shows nothing.
Below is my code for
Server:-
try
{
service = new ServerSocket(8888);
System.out.println("Server has started.");
}
catch (IOException e)
{
System.out.println(e);
}
try
{
while (connectedClient < 2)
{
server = service.accept();
connectedClient++;
BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream()));
DataOutputStream writer = new DataOutputStream(server.getOutputStream());
ClientThread clientThread = new ClientThread(server, String.valueOf(connectedClient), reader, writer);
System.out.println("Player " + connectedClient + " connected. IP Address: " + server.getInetAddress());
Thread thread = new Thread(clientThread);
thread.start();
System.out.println("Player: " + connectedClient + " thread running.");
}
System.out.println("Server is full.");
}
catch (IOException e)
{
System.out.println(e);
}
ClientThread:-
#Override
public void run()
{
try
{
while (keepRunning == true)
{
if (reader.readLine() != null)
{
String[] message = reader.readLine().split(":");
if (message[0].equalsIgnoreCase("KART1"))
{
kartNum = message[0];
if (message[1] == "INDEX")
{
kartNumIndex = message[2];
broadcastToPlayer2(kartNumIndex);
}
else if (message[1] == "X")
{
x = message[2];
broadcastToPlayer2(x);
}
else if (message[1] == "Y")
{
y = message[2];
broadcastToPlayer2(y);
}
else if (message[1] == "SPEED")
{
speed = message[2];
broadcastToPlayer2(speed);
}
}
else if (message[0].equalsIgnoreCase("KART2"))
{
kartNum = message[0];
if (message[1] == "INDEX")
{
kartNumIndex = message[2];
broadcastToPlayer1(kartNumIndex);
}
else if (message[1] == "X")
{
x = message[2];
broadcastToPlayer1(x);
}
else if (message[1] == "Y")
{
y = message[2];
broadcastToPlayer1(y);
}
else if (message[1] == "SPEED")
{
speed = message[2];
broadcastToPlayer1(speed);
}
}
}
}
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
public void broadcastToPlayer1(String value)
{
try
{
clients.get(0).writer.writeBytes(value);
clients.get(0).writer.writeBytes("\n");
clients.get(0).writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
public void broadcastToPlayer2(String value)
{
try
{
clients.get(1).writer.writeBytes(value);
clients.get(1).writer.writeBytes("\n");
clients.get(1).writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
RacingTrack (JPanel) that will get and send karts' information:-
if (playerNum == 1)
{
// send kart1 information
try
{
writer.writeBytes("KART1:INDEX:" + kart1.getKartImageIndex());
writer.writeBytes("\n");
writer.writeBytes("KART1:X:" + kart1.getXCoordinate());
writer.writeBytes("\n");
writer.writeBytes("KART1:Y:" + kart1.getYCoordinate());
writer.writeBytes("\n");
writer.writeBytes("KART1:SPEED:" + kart1.getSpeed());
writer.writeBytes("\n");
writer.flush();
kart1.draw(g, this);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
if (playerNum == 2)
{
// get kart1 information
try
{
kartImageIndex = Integer.parseInt(reader.readLine());
x = Integer.parseInt(reader.readLine());
y = Integer.parseInt(reader.readLine());
speed = Integer.parseInt(reader.readLine());
kart1.setKartImageIndex(kartImageIndex);
kart1.setXCoordinate(x);
kart1.setYCoordinate(y);
kart1.setSpeed(speed);
kart1.draw(g, this);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
// send kart2 information
try
{
writer.writeBytes("KART2:INDEX:" + kart2.getKartImageIndex());
writer.writeBytes("\n");
writer.writeBytes("KART2:X:" + kart2.getXCoordinate());
writer.writeBytes("\n");
writer.writeBytes("KART2:Y:" + kart2.getYCoordinate());
writer.writeBytes("\n");
writer.writeBytes("KART2:SPEED:" + kart2.getSpeed());
writer.writeBytes("\n");
writer.flush();
kart2.draw(g, this);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
if (playerNum == 1)
{
// get kart2 information
try
{
kartImageIndex = Integer.parseInt(reader.readLine());
x = Integer.parseInt(reader.readLine());
y = Integer.parseInt(reader.readLine());
speed = Integer.parseInt(reader.readLine());
kart2.setKartImageIndex(kartImageIndex);
kart2.setXCoordinate(x);
kart2.setYCoordinate(y);
kart2.setSpeed(speed);
kart2.draw(g, this);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
Please help :(

Related

NoSuchElementException Scanner not waiting

I am working on my first server project for school and I am receiving a NoSuchElementException when reaching the code below in my client. From my understanding, the way I have written it, the scanner should be waiting for the server to send back a string. Instead it seems to be jumping right to the exception. In the server code (second below) I have the output that is supposed to return all strings in an array. My goal is to have the client print all of the strings in the text area (status).
static void runClient() {
Socket client = null;
PrintWriter output = null;
Scanner input = null;
try {
client = new Socket("localhost", 5007);
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream());
output.println(game);
output.println(numberOfPicks);
output.flush();
pStr("Data Sent");
while (true) {
pStr("Waiting for Server");
status.appendText(input.nextLine());
if (!input.hasNext())
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (Exception e) {
}
try {
output.close();
} catch (Exception e) {
}
try {
client.close();
} catch (Exception e) {
}
}
}
private static void pStr(String string) {
System.out.println(string);
}
}
PARTIAL SERVER CODE BELOW
public void run() {
PrintWriter output = null;
Scanner input = null;
try {
// Get input and output streams.]
input = new Scanner(connection.getInputStream());
output = new PrintWriter(connection.getOutputStream());
String game;
int quickPicks;
try {
game = input.nextLine();
quickPicks = Integer.parseInt(input.nextLine());
switch (game) {
case "PowerBall":
ansStr = new pickNumbers(game, quickPicks, 69, 26).getQuickPicks();
break;
case "MegaMillions":
ansStr = new pickNumbers(game, quickPicks, 70, 25).getQuickPicks();
break;
case "Lucky4Life":
ansStr = new pickNumbers(game, quickPicks, 48, 18).getQuickPicks();
break;
default:
throw new RuntimeException("Incorrect Game");
}
} catch (Exception e) {
output.println(e.getMessage());
}
for (int i = 0; i < ansStr.length; i++) {
output.println(ansStr[i]);
//output.flush();
}
} catch (Exception e) {
pStr(e.getMessage());
} finally {
try {
input.close();
} catch (Exception e) {
}
try {
output.close();
} catch (Exception e) {
}
try {
connection.close();
} catch (Exception e) {
}
}
}
}
How about nesting status.appendText(input.nextLine()); in a test for hasNextLine e.g:
if(input.hasNextLine()){
status.appendText(input.nextLine());
}

How does TCP connection works on Android?

I am using smack for building a chat app in Android. I am using a sticky_service to hold the connection. I have a confusion that if my app goes to sleep what happens to TCP connection. I have read few answers on the page - How to make the Android device hold a TCP connection to Internet without wake lock?
It wakes up for a brief period of time - For smack I can think of it as the processmessage listener (http://www.programcreek.com/java-api-examples/index.php?api=org.jivesoftware.smack.MessageListener) is called. I am inserting data in db for that. Is there any guarantee that work will be complete or if the execution is left in between will it be started from there.
Hello dear you can use this code snippet :
protected void connect() {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
features.encryptionEnabled = false;
lastConnect = SystemClock.elapsedRealtime();
lastPingSent = SystemClock.elapsedRealtime();
this.attempt++;
try {
shouldAuthenticate = shouldBind = !account.isOptionSet(Account.OPTION_REGISTER);
tagReader = new XmlReader(wakeLock);
tagWriter = new TagWriter();
packetCallbacks.clear();
this.changeStatus(Account.State.CONNECTING);
final Bundle result = DNSHelper.getSRVRecord(account.getServer());
final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
if ("timeout".equals(result.getString("error"))) {
throw new IOException("timeout in dns");
} else if (values != null) {
int i = 0;
boolean socketError = true;
while (socketError && values.size() > i) {
final Bundle namePort = (Bundle) values.get(i);
try {
String srvRecordServer;
try {
srvRecordServer = IDN.toASCII(namePort.getString("name"));
} catch (final IllegalArgumentException e) {
// TODO: Handle me?`
srvRecordServer = "";
}
final int srvRecordPort = namePort.getInt("port");
final String srvIpServer = namePort.getString("ip");
final InetSocketAddress addr;
if (srvIpServer != null) {
addr = new InetSocketAddress(srvIpServer, srvRecordPort);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": using values from dns " + srvRecordServer
+ "[" + srvIpServer + "]:" + srvRecordPort);
} else {
addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": using values from dns "
+ srvRecordServer + ":" + srvRecordPort);
}
socket = new Socket();
socket.connect(addr, 20000);
socketError = false;
} catch (final UnknownHostException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
i++;
} catch (final IOException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
i++;
}
}
if (socketError) {
throw new UnknownHostException();
}
} else if (result.containsKey("error")
&& "nosrv".equals(result.getString("error", null))) {
//todo:change here to server.
socket = new Socket(server_ip, server port);
} else {
throw new IOException("timeout in dns");
}
final OutputStream out = socket.getOutputStream();
tagWriter.setOutputStream(out);
final InputStream in = socket.getInputStream();
tagReader.setInputStream(in);
tagWriter.beginDocument();
sendStartStream();
Tag nextTag;
while ((nextTag = tagReader.readTag()) != null) {
if (nextTag.isStart("stream")) {
processStream(nextTag);
break;
} else {
throw new IOException("unknown tag on connect");
}
}
if (socket.isConnected()) {
socket.close();
}
} catch (final UnknownHostException | ConnectException e) {
this.changeStatus(Account.State.SERVER_NOT_FOUND);
} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
this.changeStatus(Account.State.OFFLINE);
} finally {
if (wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (final RuntimeException ignored) {
}
}
}
}
enjoy your code:)

SSH connection leaving stale sessions on the server

I am programatically trying to connect to ssh running remotely. I am running a tomcat server instance. Whenever i need, from the code, i create a session, connect and execute a few commands that are needed within a try block and then close off the connection that was created as part of the finally block at all the places. Things work well and fine, but at some cases when i execute a w or netstat command on the ssh server, I see a few connections that are idle for more than a few hours and the ip address of those connections shows the connection to be from my application, but my java heap dump does not show any instance of my class in the memory, but i see ganymed related class instances in the heap.
I am using ganymed-ssh-260 library to connect to my server.
Is this something that someone has already seen?
Attaching the code snippet that connectes the ssh to the server
public class SSHExecutor{
private OutputStream stdin;
private InputStream stdout;
private InputStream stderr;
private Session sess;
private Connection conn;
public void createConnection(String hostname, int port, String userName, String password) throws Exception {
try {
conn = new Connection(hostname, port);
final boolean isAuthenticated = publicKeyAccess(hostname, userName, password);
if (!isAuthenticated) {
throw new IOException("Authentication failed.");
}
sess = conn.openSession();
final int xWidth = 90;
final int yWidth = 80;
sess.requestPTY("dumb", xWidth, yWidth, 0, 0, null);
sess.startShell();
stdin = sess.getStdin();
stdout = sess.getStdout();
stderr = sess.getStderr();
isConnectionActive = true;
final String response = getResponse();
if (response != null && response.toLowerCase().contains(ObjectConstants.CURRENTLY_NOT_AVAILABLE)) {
throw new IOException("Account is currently not available.");
}
} catch (Exception e) {
log.error("Problem in CreateConnection", e);
isConnectionActive = false;
throw e;
}
}
public String getResponse() {
final StringBuffer responseData = new StringBuffer();
try {
final int byteValue = 8192;
final byte[] buffer = new byte[byteValue];
try {
while (true) {
if ((stdout.available() == 0) && (stderr.available() == 0)) {
int conditions = 1;
if (promptString != null && promptString.length() > 0) {
final int fiveThousand = 5000;
conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA
| ChannelCondition.STDERR_DATA | ChannelCondition.EOF, fiveThousand);
} else {
conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA
| ChannelCondition.STDERR_DATA | ChannelCondition.EOF,
ObjectConstants.THOUSAND_FIVE_HUNDRED);
}
if ((conditions & ChannelCondition.TIMEOUT) != 0) {
break;
}
if ((conditions & ChannelCondition.EOF) != 0) {
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
break;
}
}
}
while (stdout.available() > 0) {
final int len = stdout.read(buffer);
if (len > 0) {
responseData.append(new String(buffer, 0, len));
}
}
while (stderr.available() > 0) {
final int len = stderr.read(buffer);
if (len > 0) {
responseData.append(new String(buffer, 0, len));
}
}
if (promptString != null && promptString.length() > 0) {
if (responseData.indexOf(promptString) != -1) {
break;
}
}
}
} catch (Exception e) {
log.error("Read Error :", e);
}
} catch (Exception e) {
log.error("getResponse Error ", e);
}
return responseData.toString();
}
public String executeCommand(String command) throws IOException {
String response = null;
if (isConnectionActive && stdin != null) {
try {
stdin.write(command.getBytes());
stdin.flush();
response = getResponse();
} catch (IOException ie) {
throw ie;
} catch (Exception e) {
log.error("Exception in executeCommandForPage()", e);
response = e.getMessage();
}
} else {
response = "Connection not active.";
}
return response;
}
public void closeConnection() {
if (stderr != null) {
try {
stderr.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
if (stdout != null) {
try {
stdout.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
if (stdin != null) {
try {
stdin.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
if (sess != null) {
try {
sess.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
log.error("Exception in closeConnection()", e);
}
}
}
}
You're creating a local Connection variable but you're testing what must be a member variable, which is always null, so you're never closing it.
If authentication fails you're leaking the connection.

Java thread illegal state exception

In a pice of code in which a class start a thread calling start method.
it throw an illegalstate exception. But if i call run() it gose well.
Can you expain me why ?
class A{
void methodA(){
T t = new T();
t.start(); // illegal state exception
t.run(); ///ok
}
}
class T extends Thread{
....
....
}
real code:
public class FileMultiServer
{
private static Logger _logger = Logger.getLogger("FileMultiServer");
public static void main(String[] args)
{
ServerSocket serverSocket = null;
boolean listening = true;
String host = "localhost";
int porta = 4444;
InetSocketAddress addr = null;
String archiveDir = System.getProperty("java.io.tmpdir");
Aes aes = new Aes();
Properties prop = new Properties();
//load a properties file
File propFile = new File("config.properties");
try {
System.out.println(propFile.getCanonicalPath());
prop.load(new FileInputStream("config.properties"));
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println(e1);
}
DBConnector.dbName = prop.getProperty("database");
DBConnector.ipDb = prop.getProperty("urlDb");
DBConnector.dbPort = prop.getProperty("dbport");
DBConnector.userName = prop.getProperty("dbuser");
DBConnector.password = aes.DeCrypt(prop.getProperty("dbpassword"));
String agent_address = prop.getProperty("agent_ip");
String agent_port = prop.getProperty("agent_port");
try {
WDAgent m_agent = new WDAgent(agent_address, Integer.parseInt(agent_port));
m_agent.run();
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
System.out.println("errore nell'agent");
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
StringWriter errors = new StringWriter();
e1.printStackTrace(new PrintWriter(errors));
_logger.debug(e1.getMessage());
_logger.debug(errors.toString());
System.out.println(e1.getMessage());
System.out.println(errors.toString());
}
String logCfg = System.getProperty("LOG");
if (logCfg != null) DOMConfigurator.configure(logCfg); else
DOMConfigurator.configure("log4j.xml");
try
{
if (args.length == 0) {
host = "localhost";
porta = 4444;
}
else if (args.length == 1) {
porta = Integer.parseInt(args[0]);
} else if (args.length == 2) {
host = args[0];
porta = Integer.parseInt(args[1]);
} else if (args.length == 3) {
host = args[0];
porta = Integer.parseInt(args[1]);
archiveDir = args[2];
} else {
_logger.info("usage: server <host> <port> | server [port] | server");
System.exit(88);
}
} catch (Exception e) {
_logger.error(e.getMessage());
_logger.info("enter a numer for argument or nothing....");
System.exit(88);
}
_logger.info("Allocating listen to: " + host + ":" + porta);
try
{
addr = new InetSocketAddress(host, porta);
serverSocket = new ServerSocket();
serverSocket.bind(addr);
} catch (Exception e) {
_logger.error(e.getMessage());
_logger.error("Could not listen on port: " + porta);
System.exit(-1);
}
_logger.info("Server listening on " + host + "-" + addr.getAddress().getHostAddress() + ":" + porta);
while (listening) {
try {
new FileMultiServerThread(serverSocket.accept(), archiveDir).start();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
try {
serverSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
}
class extends thread:
public class WDAgent extends Thread
{
private String _PID=null;
// *************************************************************************
// private - static final
// *************************************************************************
DatagramSocket socket;
boolean m_shutdown = false;
private static final Logger m_logger = Logger.getLogger(WDAgent.class);
private String getPID() {
try {
String ppid=System.getProperty("pid");
String match= "-Dpid="+ppid;
Runtime runtime = Runtime.getRuntime();
String cmd="/bin/ps -ef ";
Process process = runtime.exec(cmd);
InputStream is = process.getInputStream();
InputStreamReader osr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(osr);
String line;
while ((line = br.readLine()) != null) {
m_logger.info("line 0: "+line);
if(line.indexOf(match)!=-1 ) {
m_logger.info("line: "+line);
String[] cols=line.split(" ");
int count=0;
String val=null;
for (int k=0; k<cols.length; k++) {
if(cols[k].length()==0) continue;
count++;
if(count==3) {
// Good. I answerd the question
String pid = val;
m_logger.debug("pid processo: " + pid);
return pid;
}
val=cols[k];
}
}
}
}
catch (Exception err)
{
m_logger.error("Error retrieving PID....", err);
err.printStackTrace();
}
return null;
}
public WDAgent(String address, int port) throws IOException
{
InetSocketAddress isa = new InetSocketAddress(address, port);
socket = new DatagramSocket(isa);
m_logger.info("Agent started on (" + address + ":" + port + ")");
m_logger.info("Waiting for WD connection.");
this.start();
}
void Finalize() throws IOException
{
m_logger.info("Closing Agent.");
socket.close();
m_logger.info("Agent Closed");
}
public void Shutdown()
{
m_shutdown = true;
}
public void run()
{
byte[] buffer = new byte[1024];
int i;
while(!m_shutdown)
{
try {
String answer = "Agent PID=123456";
for (i=0; i<1024; i++)
buffer[i] = 0;
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
InetAddress client = packet.getAddress();
int client_port = packet.getPort();
m_logger.info("Received " + received + " from " + client);
if ((received.indexOf("PID") > 0) && (received.indexOf("ASK") > 0))
{
if(_PID==null) {
_PID=getPID();
}
if(_PID!=null) {
answer = "Agent PID=" + _PID;
m_logger.debug("risposta: " + answer);
DatagramPacket answ_packet = new DatagramPacket(answer.getBytes(), answer.getBytes().length, client, client_port);
socket.send(answ_packet);
} else {
m_logger.error("no PID per rispondere a watchdog .... sorry");
}
}
else
m_logger.warn("Command not recognized");
}
catch(IOException e)
{
m_logger.error(e.getMessage());
}
catch(Exception e)
{
m_logger.error(e.getMessage());
}
}
}
}
Well, if you call run(), you're just calling a method in your current thread. With start() you're attempting to start the Thread, and if it has for example already been started (or it has already stopped), you'll get an IllegalStateException.
ummm... you have already started the WDAgent Thread at constructor, so when you are trying to start again it thorws IllegalStateException.
You wanted to start it here:
...
try {
WDAgent m_agent = new WDAgent(agent_address, Integer.parseInt(agent_port));
m_agent.run(); // <-- Run that you wanted to be a start
} catch (NumberFormatException e1) {
...
But it was started in the constructor:
public WDAgent(String address, int port) throws IOException
{
InetSocketAddress isa = new InetSocketAddress(address, port);
socket = new DatagramSocket(isa);
m_logger.info("Agent started on (" + address + ":" + port + ")");
m_logger.info("Waiting for WD connection.");
this.start(); // <<----- It was already started here!!!!
}
You are running the run method twice, once in the new thread (you start it in the constructor) and one in the main thread by calling run.
t.start() is used to start the thread's execution. t.start() is used one time only. If you want to a run the thread again you will need to use t.run().

Java is using 100% of CPU using sockets

I have a Java application running on a tomcat that is in a Linux machine. This application works like a socket server, where about 15 devices are connected. Its seems like when a device sends a big message the cpu grows up until 100% usage. Te problem is that if I undeploy the application, java is still having 99% of the CPU. The application has two parts:
Socket server:
public void iniciarSocket() {
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Waiting a connection");
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
System.out.println("Client connected");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
new SocketThread(socket).start();
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
Each socket thread, which connect with each device:
public void run() {
try {
//Output channel
DataOutputStream salida;
salida = new DataOutputStream(socket.getOutputStream());
System.out.println("Client connected.... ");
byte[] buff = new byte[1024];
int bytesLeidos = 0;
socket.setSoTimeout(300000);
System.out.println("Timeout: " + socket.getSoTimeout());
while((bytesLeidos = socket.getInputStream().read(buff, 0, buff.length)) > -1) {
System.out.println("Bytes leidos: " + bytesLeidos);
if ((bytesLeidos == 70) && (Protocolo.isStatusMessage(buff))) {
Protocolo.decode(buff, salida);
} else {
int offset = 0;
while (offset < bytesLeidos) {
while ((offset + 70 <= bytesLeidos) &&(!Protocolo.isStatusMessageWithOffset(buff, offset))) {
offset++;
}
if ((offset + 70 <= bytesLeidos) &&(Protocolo.isStatusMessageWithOffset(buff, offset))) {
Protocolo.decodeWithOffset(buff, offset, salida);
offset += 70;
}
}
}
}
} catch (Exception e) {
System.out.println();
} finally {
System.out.println("Communication ended");
try {
socket.close();
} catch (Exception e) {
System.out.println("Socket not closed");
}
}
}
I don't understand what is happening and I'm traying a lot of things but I can't to solve the problem.
Seems that the problem is solved. EJP was right, if message is not multiple of 70 the loop never ends. I only had to change socketThread.
while((bytesLeidos = socket.getInputStream().read(buff, 0, buff.length)) > -1) {
System.out.println("Bytes leidos: " + bytesLeidos);
if ((bytesLeidos == 70) && (Protocolo.isStatusMessage(buff))) {
Protocolo.decode(buff, salida);
} else {
int offset = 0;
// Code changed
while (offset < bytesLeidos) {
if (Protocolo.isStatusMessageWithOffset(buff, offset)) {
// decodificar
Protocolo.decodeWithOffset(buff, offset, salida);
offset += 70;
} else {
offset++;
}
}
// End code changed
}
}
Thank you very much.

Categories

Resources