My socket isn't sending or receiving bytearrays - java

I'm trying to send bytes and receive them over my socket connection but they're not doing either. I'm not sure if its a problem to do with the way i'm sending the bytes and strings or because I don't know how to read from server and client.
Client
public class Client implements Runnable {
private Socket socket;
private ByteArrayOutputStream buffer;
private OutputStream output;
private Stage stage;
public Client() {
try {
this.socket = new Socket("localhost", 1337);
this.socket.setTcpNoDelay(true);
this.socket.setKeepAlive(true);
this.output = this.socket.getOutputStream();
InputStream input = this.socket.getInputStream();
this.buffer = new ByteArrayOutputStream();
Thread connection = new Thread(this);
connection.start();
this.sendPacket(0, ByteBuffer.allocate(16 + "TEST".length()).putInt("TEST".length()).put("TEST".getBytes(Constants.UTF8)).array());
System.out.println("[CLIENT] Successfully connected to server.");
} catch (Exception e) {
IOUtils.output("[CLIENT] Error when connecting to server.");
System.exit(1337);
}
}
#Override
public void run() {
try {
while (this.connected()) {
byte[] bytes = this.buffer.toByteArray();
Constants.received += bytes.length;
if (bytes.length < 8) return;
ByteBuffer cbuf = ByteBuffer.wrap(bytes);
int size = cbuf.getInt();
int id = cbuf.getInt();
if (bytes.length < size + 8) continue;
byte[] data = Arrays.copyOfRange(bytes, 8, 8 + size);
this.processPacket(id, data);
this.buffer.close();
(this.buffer = new ByteArrayOutputStream()).write(bytes, 8 + size, bytes.length - 8 - size);
}
System.out.println("[CLIENT] Disconnected from server.");
System.exit(1337);
} catch (Exception e) {
e.printStackTrace();
}
}
private void processPacket(int id, byte[] bytes) {
ByteBuffer data = ByteBuffer.wrap(bytes);
if (id == 0) {
System.out.println("Received packet from server with id 0");
} else if (id == 1) {
System.out.println("Received packet from server with id 1");
}
}
private void sendPacket(int id, byte[] data) {
try {
ByteBuffer bytebuffer = ByteBuffer.allocate(8 + data.length);
bytebuffer.putInt(data.length);
bytebuffer.putInt(id);
bytebuffer.put(data);
byte[] bytes = bytebuffer.array();
Constants.sent += bytes.length;
this.output.write(bytes);
this.output.flush();
} catch (IOException e) {
try {
socket.close();
} catch (IOException io) {
IOUtils.output("[CLIENT] Error with client.");
System.exit(1337);
}
}
}
private boolean connected() {
return this.socket.isConnected() && !this.socket.isInputShutdown() && !this.socket.isOutputShutdown() && !this.socket.isClosed();
}
}
ServerHandler
public class Handler implements Runnable {
private Socket socket;
private ByteArrayOutputStream buffer;
private OutputStream output;
public Handler(Socket socket) {
this.socket = socket;
try {
this.output = this.socket.getOutputStream();
InputStream input = this.socket.getInputStream();
this.buffer = new ByteArrayOutputStream();
Thread connection = new Thread(this);
connection.start();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
IOUtils.output("[HANDLER] Connection from " + socket.getInetAddress());
while (connected()) {
byte[] bytes = this.buffer.toByteArray();
if (bytes.length < 8) return;
ByteBuffer buffer = ByteBuffer.wrap(bytes);
int size = buffer.getInt();
int id = buffer.getInt();
if (bytes.length < size + 8) continue;
byte[] data = Arrays.copyOfRange(bytes, 8, 8 + size);
this.processPacket(id, data);
this.buffer.close();
(this.buffer = new ByteArrayOutputStream()).write(bytes, 8 + size, bytes.length - 8 - size);
}
IOUtils.output("[HANDLER] Client ended connection - " + socket.getInetAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendPacket(int id, byte[] data) {
try {
ByteBuffer bytebuffer = ByteBuffer.allocate(8 + data.length);
bytebuffer.putInt(data.length);
bytebuffer.putInt(id);
bytebuffer.put(data);
byte[] bytes = bytebuffer.array();
this.output.write(bytes);
this.output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void processPacket(int id, byte[] bytes) {
ByteBuffer data = ByteBuffer.wrap(bytes);
if (id == 0) {
IOUtils.output("Recieved packet with id 0");
} else if (id == 1) {
//TODO: authenticate user.
}
}
private boolean connected() {
return this.socket.isConnected() && !this.socket.isInputShutdown() && !this.socket.isOutputShutdown() && !this.socket.isClosed();
}
}
Server
public class Server implements Runnable {
private int port;
private ServerSocket sock;
public Server(int port) {
this.port = port;
launch();
}
private void launch() {
this.run();
}
#Override
public void run() {
try {
sock = new ServerSocket(port);
System.out.println("[SERVER] Server started");
while(!sock.isClosed()) {
new Handler(sock.accept());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think this problem might be with ByteArrayOutputStream. I wanted to use ByteBuffer because I heard it was much faster than normal DataInput and output streams.

You are never calling Socket#read inside of your run method... If you dont read anything you dont have anything to work with in your loop, even when you are connected!
Take a look at this Tutorial about Sockets:
https://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html

Your server code should use ServerSocket instead of Socket. Socket is used to represent Client Socket objects in Java.

Related

Java Address already in use when trying to send multiple packets

I'm trying to make a program that has a client, and intermediate host and a server. The client sends a packet to the host, the host sends it to the server and than the server sends a packet back to the host who sends it to the client. This should repeat 11 times.
Here is my code:
public class SimpleEchoClient {
DatagramPacket sendPacket, receivePacket;
DatagramSocket sendReceiveSocket;
public SimpleEchoClient()
{
try {
sendReceiveSocket = new DatagramSocket();
} catch (SocketException se) { // Can't create the socket.
se.printStackTrace();
System.exit(1);
}
}
public byte[] createWriteByte() {
byte[] msg = new byte[100];
int position = 2;
Path path = Paths.get("test.txt");
String fileName = path.getFileName().toString();
//In datagrampackets, our data needs to be converted into bytes
msg = new byte[100];
msg[0] = 0x00;
msg[1] = 0x02;
for(int i=0; i<fileName.getBytes().length; i++) {
msg[position] = fileName.getBytes()[i];
position++;
}
msg[position] = 0x00;
String mode = "netascii";
position++;
for(int i = 0; i < mode.getBytes().length; i++) {
msg[position] = mode.getBytes()[i];
position++;
}
msg[position] = 0;
return msg;
}
public byte[] createReadByte() {
byte[] msg = new byte[100];
int position = 2;
Path path = Paths.get("test.txt");
String fileName = path.getFileName().toString();
//In datagrampackets, our data needs to be converted into bytes
msg = new byte[100];
msg[0] = 0x00;
msg[1] = 0x01;
for(int i=0; i<fileName.getBytes().length; i++) {
msg[position] = fileName.getBytes()[i];
position++;
}
msg[position] = 0x00;
String mode = "netascii";
position++;
for(int i = 0; i < mode.getBytes().length; i++) {
msg[position] = mode.getBytes()[i];
position++;
}
msg[position] = 0;
return msg;
}
public void sendAndReceive(boolean checkRead)
{
Path path = Paths.get("test.txt");
String fileName = path.getFileName().toString();
//In datagrampackets, our data needs to be converted into bytes
byte[] msg;
if(checkRead) {
msg = createReadByte();
checkRead = false;
}else{
msg = createWriteByte();
checkRead = true;
}
String str = new String(msg);
System.out.println(str);
System.out.println("Hello");
System.out.println(msg);
try {
sendPacket = new DatagramPacket(msg, msg.length,
InetAddress.getLocalHost(), 5000);
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(1);
}
try {
sendReceiveSocket.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
sendReceiveSocket.close();
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
System.out.println("Client: Packet sent.\n");
//NOW TO RECEIVE THE DATA
DatagramSocket receiveSocket = null;
try {
receiveSocket = new DatagramSocket(5000);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte data[] = new byte[4];
receivePacket = new DatagramPacket(data, data.length);
try {
// Block until a datagram is received via sendReceiveSocket.
receiveSocket.receive(receivePacket);
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
}
// Process the received datagram.
for(int j =0; j < data.length; j++) {
System.out.println(data[j] & 0xff);
}
// We're finished, so close the socket.
sendReceiveSocket.close();
}
public static void main(String args[])
{
boolean checkRead = true;
int count =0;
for(int i = 0; i<10; i++) {
System.out.println("Count:" + count);
SimpleEchoClient c = new SimpleEchoClient();
c.sendAndReceive(checkRead);
}
}
}
public class IntermediateHost {
DatagramSocket receiveFromClient, receiveFromServer;
DatagramPacket receiveClientPack, sendClientPacket, receiveServerPacket, sendServerPacket;
public IntermediateHost() {
try {
receiveFromClient = new DatagramSocket(5000);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void receiveAndEcho() {
byte [] b = new byte[100];
//When we receive the packet we need to store it in a datagrampacket which is initally empty
receiveClientPack = new DatagramPacket(b, b.length);
InetAddress ip = null;
try {
receiveFromClient.receive(receiveClientPack);
ip = InetAddress.getByName("localhost");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String message = new String(b);
System.out.println(message);
System.out.println(b);
int port = 3001;
sendClientPacket = new DatagramPacket(b, b.length, ip, port);
try {
receiveFromClient.send(sendClientPacket);
} catch (IOException e1) {
e1.printStackTrace();
}
receiveFromClient.close();
//SEND BACK TO THE CLIENT
try {
Thread.sleep(5000);
receiveFromServer = new DatagramSocket(3001);
} catch (InterruptedException | SocketException e1) {
e1.printStackTrace();
}
byte [] b1 = new byte[4];
//When we receive the packet we need to store it in a datagrampacket which is initally empty
receiveServerPacket = new DatagramPacket(b1, b1.length);
//This method will wait for the incoming packet and it will copy all values from that packet
//into receiveClientPack..so at this point the byte array will not be empty
try{
receiveFromServer.receive(receiveServerPacket);
}catch (Exception e) {
System.out.println(e);
}
for(int i =0;i < b1.length; i++) {
System.out.println(b1[i] & 0xff);
}
InetAddress ip1 = null;
try {
ip1 = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
int port1 = 5000;
sendServerPacket = new DatagramPacket(b1, b1.length, ip1, port1);
try {
receiveFromServer.send(sendServerPacket);
} catch (IOException e) {
e.printStackTrace();
}
receiveFromServer.close();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws IOException, InterruptedException {
while(true) {
IntermediateHost inter = new IntermediateHost();
inter.receiveAndEcho();
}
}
}
public class SimpleEchoServer {
DatagramPacket sendPacket, receivePacket;
DatagramSocket sendSocket, receiveSocket;
public SimpleEchoServer()
{
try {
sendSocket = new DatagramSocket();
receiveSocket = new DatagramSocket(3001);
} catch (SocketException se) {
se.printStackTrace();
System.exit(1);
}
}
public byte[] sendBackRead() {
byte [] bytesToSend = new byte[4];
bytesToSend[0] = 0x00;
bytesToSend[1] = 0x03;
bytesToSend[2] = 0x00;
bytesToSend[3] = 0x01;
return bytesToSend;
}
public byte[] sendBackWrite() {
byte [] bytesToSend = new byte[4];
bytesToSend[0] = 0x00;
bytesToSend[1] = 0x04;
bytesToSend[2] = 0x00;
bytesToSend[3] = 0x00;
return bytesToSend;
}
public boolean checkRead(byte[] msg) {
if(msg[1] == 1) {
return true;
}
return false;
}
public boolean checkWrite(byte[] msg) {
if(msg[1] == 2) {
return true;
}
return false;
}
public void receiveAndEcho() throws UnknownHostException
{
byte data[] = new byte[100];
receivePacket = new DatagramPacket(data, data.length);
System.out.println("Server: Waiting for Packet.\n");
try {
System.out.println("Waiting..."); // so we know we're waiting
receiveSocket.receive(receivePacket);
} catch (IOException e) {
System.out.print("IO Exception: likely:");
System.out.println("Receive Socket Timed Out.\n" + e);
e.printStackTrace();
System.exit(1);
}
boolean checkRead = checkRead(data);
boolean checkWrite = checkWrite(data);
String message = new String(data);
System.out.println(message);
receiveSocket.close();
// Slow things down (wait 5 seconds)
try {
Thread.sleep(5000);
} catch (InterruptedException e ) {
e.printStackTrace();
System.exit(1);
}
byte[] bytesToSend = null;
System.out.println(data[1]);
if(checkRead) {
bytesToSend = sendBackWrite();
}else if(checkWrite) {
bytesToSend = sendBackRead();
}
for(int i =0;i < bytesToSend.length; i++) {
System.out.println(bytesToSend[i] & 0xff);
}
InetAddress ip = InetAddress.getLocalHost();
sendPacket = new DatagramPacket(bytesToSend, bytesToSend.length,
ip, 3001);
// Send the datagram packet to the client via the send socket.
try {
sendSocket.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("Server: packet sent");
// We're finished, so close the sockets.
sendSocket.close();
receiveSocket.close();
}
public static void main( String args[] ) throws UnknownHostException
{
while(true) {
SimpleEchoServer c = new SimpleEchoServer();
c.receiveAndEcho();
}
}
}
Now this code works if I were to only send one packet to the host, which sends to the server which returns another packet to the client from the host. However when I try to send more than one packet I get an error. To send more than one packet I basically create a loop in the main that simply calls the methods 11 times and i place a while loop in the server and host to have it running continuously in order to wait for packets. To see it run once, just eliminate the while loops in the main function of all three classes.
Any help as to how I can fix this error is greatly appreciated! Thanks!
On each call to the SimpleEchoClient c = new SimpleEchoClient();, your code tries to create a client on port 5000. Since you already have a client running on the same port, the exception is thrown.
So do it only once and send the packet 11 times.
public static void main(String args[])
{
boolean checkRead = true;
int count =0;
SimpleEchoClient c = new SimpleEchoClient();
for(int i = 0; i<=10; i++) {
System.out.println("Count:" + count);
c.sendAndReceive(checkRead);
}
}
Check how I have changed the loop condition to <=10 to make sure that 11 packets are sent.

Java android get byte[] from server

Hi I want to do something like this : I want to send a data to server and wait for receiver byte[] from server . the server will send the array when everything gets. But I want do some timeout becouse sometimes server don't get everything and nothing send.
I do this but it doesn't work. My application always wait for byte[]
public class MyClientTask1 extends AsyncTask<Void, Void, byte[]> {
String dstAddress;
int dstPort;
String response = "";
byte[] data;
int count;
MyClientTask1(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
byte[] buffer = new byte[1024];
#Override
protected byte[] doInBackground(Void... arg0) {
// if (pingHost(1000)) {
socket = null;
try {
socket = new Socket(dstAddress, dstPort);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "10";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
InputStream stream = socket.getInputStream();
data = new byte[100];
count = stream.read(data);
if(stream.read() == null)
Thread.sleep(2000);
count = stream.read(data);
if( count != 0){
data = null;
}
// while ((count = stream.read(data)) != -1){
// count=stream.read(data);
// }
} catch (UnknownHostException e) {
e.printStackTrace();
isSuccsess = false;
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
Log.d("la", "nie udało sie");
isSuccsess = false;
response = "IOException: " + e.toString();
} catch (InterruptedException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
if(bytes != null) {
if (bytes[0] == (byte) 0xF && bytes[1] == (byte) 0xA && bytes[2] == (byte) 0xA && bytes[3] == (byte) 0xD) {
showToast("zgadza się");
} else {
showToast("nie zgadza się");
}
}
else{
showToast("nie ma nic");
}
pbWheel.setVisibility(View.INVISIBLE);
}

Java: Send and receive byte array

Well, I want to write a simple java client-server-programme, which exchanges byte arrays over tcp-sockets.
/* Server */
public class Server {
private ServerSocket Server = null;
private Socket Client = null;
public static void main(String[] args) {
Server A = new Server();
A.runServer();
A.listenServer();
}
public void runServer() {
try {
Server = new ServerSocket(1234);
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
System.exit(-1);
}
}
public void listenServer() {
try {
while (true) {
System.out.println("Waiting...");
Client = Server.accept();
System.out.println("Got something new");
readMessage(Client);
}
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
}
public byte [] readMessage (Socket socket) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1];
int len = -1;
while((len = socket.getInputStream().read(buf))!=-1){
baos.write(buf, 0, len);
}
for (int i=0; i<baos.toByteArray().length; i++) {
System.out.println(baos.toByteArray()[i]);
}
return baos.toByteArray();
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
return null;
}
public void writeMessage (Socket socket, String Message) {
try {
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
printWriter.print(Message);
printWriter.flush();
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
}
}
/* Client */
public class Client {
public static void main(String[] args) {
Client B = new Client();
B.runClient();
}
public void runClient () {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 1234);
}
catch (Exception e) {
System.out.println("Client fault: "+e.getMessage());
}
byte [] Tmp = new byte[10];
for (int i=0; i<Tmp.length; i++) {
Tmp[i] = 1;
}
writeMessage(socket, Tmp);
for (int i=0; i<10; i++) {
byte [] Message = readMessage(socket);
System.out.println(Message);
}
}
public void writeMessage (Socket socket, byte [] myByteMessage) {
try {
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.write(myByteMessage, 0, myByteMessage.length);
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
printWriter.print(myByteMessage);
printWriter.flush();
}
catch (Exception e) {
System.out.println("Could not send data over TCP");
return;
}
}
public byte [] readMessage (Socket socket) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1];
int len = -1;
while((len = socket.getInputStream().read(buf))!=-1){
baos.write(buf, 0, len);
}
for (int i=0; i<baos.toByteArray().length; i++) {
System.out.println(baos.toByteArray()[i]);
}
System.out.println("Test");
return baos.toByteArray();
}
catch (Exception e) {
System.out.println("Server fault: "+ e.getMessage());
}
return null;
}
}
The problem is, that the client send something to the server but the server doesn't receive anything, so he hangs at the readMessage function.
On the other hand, the client receive some weird stuff, but not the response from the server.
The server receives bytes, but it never leaves the while loop because read() never returns -1. read() returns -1 when the end of the stream is reached. And that happens only when the client closes the socket output stream. Since the client never closes the output stream, the server keeps waiting for the more bytes to come.
Side note: your code is hard to read because you don't respect the standard Java naming conventions: variables start with a lowercase letter.

How to answer to my client from my server?

I've got the following code for my server:
try
{
Socket = serverSocket.accept();
inputStreamReader = new InputStreamReader(Socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
message = bufferedReader.readLine();
switch(message)
{
case "GET / HTTP/1.1":
{
break;
}
default:
{
System.out.println(message);
}
}
inputStreamReader.close();
Socket.close();
}
catch(Exception e)
{
System.out.println("Problem while waiting for messages (" + e.toString() + ")");
}
and this code for my (Android) Client:
private String GetPC(String strToPC)
{
final String strToPCFinal = strToPC;
Thread SendingThread = new Thread()
{
public void run()
{
try
{
client = new Socket("192.168.178.22", 14510);
printwriter = new PrintWriter(client.getOutputStream());
printwriter.write(strToPCFinal);
printwriter.flush();
printwriter.close();
client.close();
}
catch(Exception e)
{
System.out.println("Problem while sending test message (" + e.toString() + ")");
}
}
};
SendingThread.start();
return "";
}
My question now is: How can I get an answer (if the text is successfully transmitted to my PC) back to my Android client?
private String readReply(SocketChannel socket) throws IOException {
final StringBuilder reply = new StringBuilder();
final ByteBuffer buffer = ByteBuffer.allocate(512);
int numBytesRead;
do {
numBytesRead = socket.read(buffer);
if (numBytesRead > 0) {
buffer.flip();
reply.append(decoder.decode(buffer).toString());
buffer.clear();
if (reply.indexOf(".") > -1) {
break;
}
}
} while (numBytesRead > -1);
socket.close();
return reply.toString();
}
Use the snippet below to send to server (if localhost)
private String send(String command) throws IOException {
final SocketAddress address = new InetSocketAddress("10.0.2.2", PORT);
final SocketChannel socket = SocketChannel.open(address);
final CharBuffer buffer = CharBuffer.wrap(command);
socket.write(encoder.encode(buffer));
final String reply = readReply(socket); // Get response
socket.close();
return reply;
}

Java - sending packets via UDP

In my android app, I am sending messages via UDP. I followed this and this.
However, I am not able to send the initial packet from the client to the server. Please let me know if I am doing something wrong in my code below:
class serverCommunicationThread implements Runnable
{
public void run()
{
try {
serverSocket = new DatagramSocket(STATICPORT);
ServerReceiveMessageThread rcvMsgThread = new ServerReceiveMessageThread(serverSocket);
new Thread(rcvMsgThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
This is the ServerReceiveMessageThread class:
class ServerReceiveMessageThread implements Runnable
{
DatagramSocket clientSocket;
byte[] buffer = new byte[108];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
ServerReceiveMessageThread(DatagramSocket clientSocket)
{
this.clientSocket = clientSocket;
}
#Override
public void run()
{
int counter = 0;
MsgStruct recvMsgStruct = null;
try {
ByteArrayOutputStream baosServer = new ByteArrayOutputStream();
serializeServer = new ObjectOutputStream(baosServer);
clientSocket.receive(packet);
ByteArrayInputStream baosRecv = new ByteArrayInputStream(buffer);
deserializeServer = new ObjectInputStream(baosRecv);
while(true)
{
try {
recvMsgStruct = (MsgStruct) deserializeServer.readObject();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
boolean retVal = serverSendMessage(clientSocket, recvMsgStruct, baosServer.toByteArray());
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
The serverSendMessage method:
public boolean serverSendMessage(DatagramSocket clientSocket, MsgStruct msgStruct, byte[] buf)
{
MsgStruct recvMsgStruct = new MsgStruct();
recvMsgStruct.pingPong = true;
recvMsgStruct.msgId = msgStruct.msgId;
recvMsgStruct.bufferMsg = msgStruct.bufferMsg;
try {
serializeServer.writeObject(recvMsgStruct);
serializeServer.flush();
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(mobileIP), STATICPORT);
clientSocket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
The code for the client send/receive is similar to that of the server. I get a NullPointerException here.
serializeClient.writeObject(mobileSendMsgStruct);
public boolean mobileSendMessage(int msgId)
{
MsgStruct mobileSendMsgStruct = new MsgStruct();
mobileSendMsgStruct.bufferMsg = new byte[100];
mobileSendMsgStruct.pingPong = false;
mobileSendMsgStruct.msgId = msgId;
rand.nextBytes(mobileSendMsgStruct.bufferMsg);
try {
sendTime = System.nanoTime();
serializeClient.writeObject(mobileSendMsgStruct); /*I get a NullPointerException here*/
serializeClient.flush();
byte[] sendBuf = baosSend.toByteArray();
DatagramPacket packet = new DatagramPacket(sendBuf, sendBuf.length, InetAddress.getByName(staticIP), STATICPORT);
mobileSocket.send(packet);
outPing.write(Long.toString(sendTime) + ", " + String.valueOf(mobileSendMsgStruct.msgId) + ", " + String.valueOf(mobileSendMsgStruct.bufferMsg) + " | ");
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
return true;
}

Categories

Resources