Using client-server to move object on screen - java

So I'm trying to use a client-server with a keyListener. When the messages "#left" or "#right" are sent to the server, it should update the graphical object and shift it to the left by calling the map.repaint() method. Instead, it shifts the object once and then no further responses happen. Posted below is the code. Can someone offer a solution?
// the server
#Override
protected void handleMessageFromClient(Object msg, ConnectionToClient client) {
// TODO Auto-generated method stub
if(msg instanceof String)
{
String message = msg.toString();
if(message.equals("#connect"))
{
String error = "Already connected";
Matcher match = null;
for (int i = 0; i < matches.size(); i++)
{
if(matches.get(i).contains(client))
{
match = matches.get(i);
try {
client.sendToClient(error);
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Could not send #connect error message");
}
break;
}
}
if(match == null)
{
Matcher matcher = new Matcher(this,client);
matches.add(matcher);
}
}
if(message.equals("#left"))
{
action("left",client);
}
if(message.equals("#right"))
{
action("right",client);
}
if(message.equals("#jump"))
{
action("jump",client);
}
if(message.startsWith("#shoot"))
{
String error = "please connect";
Matcher match = null;
for (int i = 0; i < matches.size(); i++)
{
if(matches.get(i).contains(client))
{
match = matches.get(i);
break;
}
}
if(match == null)
{
try {
client.sendToClient(error);
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Could not send #left error message");
}
}else
{
match.moveLeft(client);
}
}
if(message.contains("?"))
try {
client.sendToClient(msg);
} catch (IOException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (msg instanceof Integer)
try {
client.sendToClient(msg);
} catch (IOException ex) {
System.out.println("Message not sent. Turning off.");
}
private void action(String errorm, ConnectionToClient client)
{
String error = "please connect";
Matcher match = null;
for (int i = 0; i < matches.size(); i++)
{
if(matches.get(i).contains(client))
{
match = matches.get(i);
break;
}
}
if(match == null)
{
try {
client.sendToClient(error);
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Could not send #" + errorm + " error message");
}
}else
{
if(errorm.equals("left"))
{
match.moveLeft(client);
}else if(errorm.equals("right"))
{
match.moveRight(client);
}
else if(errorm.equals("jump"))
{
match.updateJump(client);
}
}
}
//the matcher class which controls graphics
public void moveLeft(ConnectionToClient client)
{
for (int i = 0; i < players.length; i++)
{
if(players[i].getId() == client.getId())
{
if(i == 0)
{
synchronized(this)
{
map.updateFirstPlayer(map.getx1Rec1() - 5, map.gety1Rec1(), map.getx2Rec1(), map.gety2Rec1());
map.repaint();
map.updateUI();
}
}
if(i == 1)
{
synchronized(this)
{
map.updateSecondPlayer(map.getx1Rec2() - 5, map.gety1Rec2(), map.getx2Rec2(), map.gety2Rec2());
map.repaint();
map.updateUI();
}
}
break;
}
}
try {
client.sendToClient(map);
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Could not update left");
}
}
public void moveRight(ConnectionToClient client)
{
for (int i = 0; i < players.length; i++)
{
if(players[i].getId() == client.getId())
{
if(i == 0)
{
synchronized(this)
{
map.updateFirstPlayer(map.getx1Rec1() + 5, map.gety1Rec1(), map.getx2Rec1(), map.gety2Rec1());
map.repaint();
map.updateUI();
}
}
if(i == 1)
{
synchronized(this)
{
map.updateSecondPlayer(map.getx1Rec2() + 5, map.gety1Rec2(), map.getx2Rec2(), map.gety2Rec2());
map.repaint();
map.updateUI();
}
}
break;
}
}
try {
client.sendToClient(map);
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Could not update right");
}
}
public void updateJump(ConnectionToClient client)
{
for (int i = 0; i < players.length; i++)
{
if(players[i].getId() == client.getId())
{
if(i == 0)
{
synchronized(this)
{
for (int j = 0; j < 50; j+=5)
{
map.updateFirstPlayer(map.getx1Rec1() , map.gety1Rec1() + j, map.getx2Rec1(), map.gety2Rec1());
/*try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
map.repaint();
}
}
}
if(i == 1)
{
synchronized(this)
{
for (int j = 0; j < 50; j+=5)
{
map.updateSecondPlayer(map.getx1Rec2(), map.gety1Rec2() + j, map.getx2Rec2(), map.gety2Rec2());
/*try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
map.repaint();
map.updateUI();
}
}
}
break;
}
}
try {
client.sendToClient(map);
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Could not return jump");
}
}

Related

Java JSSC serial read consuming 100% CPU

I am trying to read GPS data from a serial port(ttyACM0) in java using jssc jar which I need to display as a label in a JavaFx application. I have a created a thread for reading the GPS data but this thread is consuming 100% CPU(checked using top command + Shift H) because of which my GUI is getting freezed. This is a sample code I have written for reading GPS data
Serial Interface
import jssc.*;
public class SerInterface {
String portName;
int baud;
boolean lineMode;
// The chosen Port itself
SerialPort port;
public byte[] recvBuff;
public SerInterface(String portName, int baud, boolean lineMode) {
this.portName = portName;
this.baud = baud;
this.lineMode = lineMode;
recvBuff = new byte[8192];
openPort();
if((port == null) || (!port.isOpened()))
System.out.println(portName + " not opened successfully");
}
void openPort() {
port = new SerialPort(portName);
if(port == null)
return;
try {
port.openPort();
} catch (SerialPortException e) {
e.printStackTrace();
}
try {
if(port.isOpened())
port.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
else
return;
} catch (SerialPortException e) {
e.printStackTrace();
}
System.out.println(portName + " opened successfully");
}
public int recvData() {
int len = 0;
if(port.isOpened()) {
try {
byte[] buff = port.readBytes();
if((buff == null) || (buff.length == 0))
return 0;
len = buff.length;
if(len > recvBuff.length)
len = recvBuff.length;
System.arraycopy(buff, 0, recvBuff, 0, len);
buff = null;
} catch (SerialPortException e) {
e.printStackTrace();
}
}
return len;
}
public void sendData(byte[] sendBuff, int len) {
if(port.isOpened()) {
try {
port.writeBytes(sendBuff);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
public boolean validatePort() {
if(!port.isOpened()) {
openPort();
if(port.isOpened())
return true;
else
return false;
}
else
return true;
}
public void flushPort() {
if(port.isOpened()) {
try {
port.purgePort(SerialPort.PURGE_RXCLEAR | SerialPort.PURGE_TXCLEAR);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
public void closePort() {
if(port.isOpened()) {
try {
port.closePort();
System.out.println("port closed");
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
}
GPSReceiver thread extends SerInterface and implements Runnable
#Override
public void run() {
flushPort();
while(true) {
if(!validatePort()) {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
int dataLength = recvData();
if(dataLength < 2)
continue;
try {
InputStream gpsStream = new ByteArrayInputStream(recvBuff, 0, dataLength);
BufferedReader br = new BufferedReader(new InputStreamReader(gpsStream, StandardCharsets.US_ASCII));
while(true) {
try {
if (!((output = br.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
extractData();
}
}
catch(NullPointerException e) {
e.printStackTrace();
}
}
Main Thread
GPSInterface objGPSThreadInterface = new GPSInterface(GPSPortName, 9600, true);
GPSThreadInt = new Thread(objGPSThreadInterface, "GPSINT");
I am using jdk-13.0.1 and jssc-2.9.1 jar

Elastic Search : cannot write a field name expecting a value

Okay what I am trying to achieve here is parsing a json string and separating its fields and assigning them to variables. Next I am creating a builder to send data to the elastic for indexing. But I am getting this error which is really bugging me. I am unable to move forward.
for (int i = 0; i < jsonarray.length(); i++) {
try {
obj = jsonarray.getJSONObject(i);
System.out.println(obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
type = obj.getString("type");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Values for select");
try {
JSONArray jContent = (JSONArray) obj.get("values");
for (int iterate = 0; iterate < jContent.length(); iterate++) {
JSONObject inner = jContent.getJSONObject(iterate);
String inner_label = (String) inner.get("label");
String val = (String) inner.get("value");
boolean sel;
try {
sel = (boolean) inner.get("selected");
} catch (JSONException j) {
sel = false;
}
builder.startObject("Extras").field("inner_lab", inner_label).field("inner_value", val).field("Selected", sel).endObject();
}
} catch (JSONException e) {
}
try {
label = obj.getString("label");
} catch (JSONException e) {
e.printStackTrace();
}
try {
access = obj.getBoolean("access");
} catch (JSONException e) {
access = false;
}
try {
role = obj.getString("role");
} catch (JSONException e) {
role = null;
}
try {
subtype = obj.getString("subtype");
} catch (JSONException e) {
subtype = null;
}
try {
maxlength = obj.getString("maxlength");
} catch (JSONException e) {
maxlength = null;
}
try {
name = obj.getString("name");
} catch (JSONException e) {
name = null;
}
try {
description = obj.getString("description");
} catch (JSONException e) {
description = null;
}
try {
classname = obj.getString("className");
} catch (JSONException e) {
classname = null;
}
try {
placeholder = obj.getString("placeholder");
} catch (JSONException e) {
placeholder = null;
}
try {
value = obj.getString("value");
} catch (JSONException e) {
value = null;
}
try {
required = obj.getBoolean("required");
} catch (JSONException e) {
required = false;
}
try {
toggle = obj.getBoolean("toggle");
} catch (JSONException e) {
toggle = false;
}
try {
inline = obj.getBoolean("inline");
} catch (JSONException e) {
inline = false;
}
try {
enableother = obj.getBoolean("other");
} catch (JSONException e) {
enableother = false;
}
try {
multipleFiles = obj.getBoolean("multiple");
} catch (JSONException e) {
multipleFiles = false;
}
try {
style = obj.getString("style");
} catch (JSONException e) {
style = null;
}
try {
min = obj.getString("min");
} catch (JSONException e) {
min = null;
}
try {
max = obj.getString("max");
} catch (JSONException e) {
max = null;
}
try {
step = obj.getString("step");
} catch (JSONException e) {
step = null;
}
try {
rows = obj.getString("rows");
} catch (JSONException e) {
rows = null;
}
// //Indexing Data..
(HERE) builder.startObject("values").field("access", access).field("role", role).field("subtype", subtype)
.field("maxlength", maxlength).field("name", name).field("description", description)
.field("className", classname).field("label", label).field("placeholder", placeholder)
.field("value", value).field("required", required).field("style", style).field("toggle", toggle)
.field("inline", inline).field("other", enableother).field("multiple", multipleFiles)
.field("content", content).field("min", min).field("max", max).field("step", step)
.field("rows", rows).endObject();
builder.endObject();
resp = client.prepareIndex("clien", userName).setSource(builder).execute().actionGet();
}
}
At (HERE) position erro keeps showing up..Cannot write a field name expecting a value.
Also is there a better way to achieve what I am trying to do here. thanks for the help.

org.json.JSONException: JSONObject["values"] is not a JSONArray."

This my json array.
[
{
"type":"select",
"label":"Select",
"className":"form-control",
"name":"select-1497355331262",
"values":[
{
"label":"Option 1",
"value":"option-1",
"selected":true
},
{
"label":"Option 2",
"value":"option-2"
},
{
"label":"Option 3",
"value":"option-3"
}
]
}
]
My Appraoch :
JSONArray js = null;
try {
js = new JSONArray(json);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject obj = null;
for (int i = 0; i < js.length(); i++) {
try {
obj = js.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
type = obj.getString("type");
} catch (JSONException e) {
type = null;
}
System.out.println("Type : " + type);
try {
JSONArray jContent = obj.getJSONArray("values");
System.out.println(jContent.toString());
for (int iterate = 0; iterate < jContent.length(); iterate++) {
JSONObject inner = jContent.getJSONObject(iterate);
String inner_label = (String) inner.get("label");
System.out.println(inner_label);
String val = (String) inner.get("value");
boolean sel;
try {
sel = (boolean) inner.get("selected");
} catch (JSONException j) {
sel = false;
}
System.out.print(inner_label);
System.out.print(" " + val);
System.out.println(" " + sel);
}
} catch (JSONException e) {
System.out.println("There is some error");
}
try {
label = obj.getString("label");
} catch (JSONException e) {
e.printStackTrace();
}
try {
access = obj.getBoolean("access");
} catch (JSONException e) {
access = false;
}
try {
role = obj.getString("role");
} catch (JSONException e) {
role = null;
}
try {
subtype = obj.getString("subtype");
} catch (JSONException e) {
subtype = null;
}
try {
maxlength = obj.getString("maxlength");
} catch (JSONException e) {
maxlength = null;
}
try {
name = obj.getString("name");
} catch (JSONException e) {
name = null;
}
try {
description = obj.getString("description");
} catch (JSONException e) {
description = null;
}
try {
classname = obj.getString("className");
} catch (JSONException e) {
classname = null;
}
try {
placeholder = obj.getString("placeholder");
} catch (JSONException e) {
placeholder = null;
}
try {
value = obj.getString("value");
} catch (JSONException e) {
value = null;
}
try {
required = obj.getBoolean("required");
} catch (JSONException e) {
required = false;
}
try {
toggle = obj.getBoolean("toggle");
} catch (JSONException e) {
toggle = false;
}
try {
inline = obj.getBoolean("inline");
} catch (JSONException e) {
inline = false;
}
try {
enableother = obj.getBoolean("other");
} catch (JSONException e) {
enableother = false;
}
try {
multipleFiles = obj.getBoolean("multiple");
} catch (JSONException e) {
multipleFiles = false;
}
try {
style = obj.getString("style");
} catch (JSONException e) {
style = null;
}
try {
min = obj.getString("min");
} catch (JSONException e) {
min = null;
}
try {
max = obj.getString("max");
} catch (JSONException e) {
max = null;
}
try {
step = obj.getString("step");
} catch (JSONException e) {
step = null;
}
try {
rows = obj.getString("rows");
} catch (JSONException e) {
rows = null;
}
I am able to get all other objects values I am unable to read the values array. I have written the code for it but its directly going to the catch block printing the error message "There is some error". Thnaks for the help.
Solved...Values was not an array it was an object....So here's what I did. It worked.
try {
String j2 = obj.getString("values");
JSONArray jContent = new JSONArray(j2);
for (int iterate = 0; iterate < jContent.length(); iterate++) {
JSONObject inner = jContent.getJSONObject(iterate);
String inner_label = (String) inner.get("label");
System.out.println(inner_label);
String val = (String) inner.get("value");
boolean sel;
try {
sel = (boolean) inner.get("selected");
} catch (JSONException j) {
sel = false;
}
System.out.print(inner_label);
System.out.print(" " + val);
System.out.println(" " + sel);
}

Java Client Server "Socket is closed"

I'm working on a really simple Java Client / Server system (Just to get my feet wet with sockets). For some reason, I keep getting a "Socket is closed" error... here is my code..
Server File
public class Server {
public static ServerSocket s = null;
public static void main(String[] args) {
//Create the server socket
int port = 1111;
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
try {
s = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s.setSoTimeout(0);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Runnable r = new Runnable() {
public void run() {
while (true) {
Socket caught = null;
try {
caught = Server.s.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (caught == null) {
return;
}
InputStream is = null;
try {
is = caught.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
handleCommand(output, caught);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
public static void handleCommand(String in, Socket s1) {
if (in.equalsIgnoreCase("test")) {
System.out.println("Recieved Test Command..");
System.out.println("Sending response..");
PrintStream ps = null;
try {
ps = new PrintStream(s1.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
ps.close();
}
}
}
Client File
public class Client {
public static Socket s = null;
public static void main(String[] args) {
int port = 1111;
String server = "localhost";
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
if (args.length > 1) {
server = args[1];
}
try {
s = new Socket(server, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (s != null) {
Runnable r = new Runnable() {
public void run() {
while (true) {
InputStream is = null;
try {
is = s.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
PrintStream ps = null;
try {
ps = new PrintStream(s.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Sending Test message..");
try {
ps.println("test");
} catch (Exception e) {
System.out.println("Error: - " + e.getMessage());
}
}
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
}
I get the error in the client on line 41 and then a NullPointerException on line 46..
Thanks in advance for any help. I'm just trying to learn here.
in the server on line 61, when you do your first read, your client didn't had the oportunity to send data, so it don't stops in the loop and move forward to close the reader on line 68.
Try to create a class to handle incoming connections at the server, that makes easier to think about what to do in the server, something like ClientHandler would be a good choice ;)
have fun !

JSONException: Misplaced object

This is my code:
JSONStringer result = new JSONStringer();
for (long i = start; i <= end; i = i + day) {
ttm.put("$gte", "" + i);
ttm.put("$lte", "" + (i + day));
//code code code
int count = statisticCollection.find(query).count();
try {
result.object().key("ttm").value(i).key("count").value(count);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
result.endObject();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I then get a JSONException. I also tried creating and ending the object with a different try-catch block, as below:
JSONStringer result = new JSONStringer();
try {
result.object();
} catch (Exception e) {
e.printStackTrace();
}
for (long i = start; i <= end; i = i + day) {
ttm.put("$gte", "" + i);
ttm.put("$lte", "" + (i + day));
//code code code
long count = statisticCollection.find(query).count();
try {
result.key("ttm").value(i).key("count").value(count);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
result.endObject();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and creating and ending the JSONStringer in the for loop itself, as follows:
JSONStringer result = new JSONStringer();
for (long i = start; i <= end; i = i + day) {
ttm.put("$gte", "" + i);
ttm.put("$lte", "" + (i + day));
//code code code
int count = statisticCollection.find(query).count();
try {
result.object().key("ttm").value(i).key("count").value(count).endObject();
} catch (JSONException e) {
e.printStackTrace();
}
What am I doing wrong?
Thanks.
You need to use an array:
JSONStringer result = new JSONStringer();
JSONWriter array = result.array();
for (long i = start; i <= end; i = i + day) {
ttm.put("$gte", "" + i);
ttm.put("$lte", "" + (i + day));
//code code code
int count = statisticCollection.find(query).count();
try {
array.object().key("ttm").value(i).key("count").value(count).endObject();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
array.endArray();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories