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.
Related
It's my first time working with sockets, in order to get a better understanding of what's going on I decided to build a client server chat application which can support several users.
At first, I used DataInputStream / DataOutputStream to communicate and everything works well. But I would like to switch to an ObjectStream and that's where the problem occurs. Once I replace all the DataInputStream / DataOutputStream by ObjectInputStream / ObjectOutputStream, I'm no longer able to print the retrieved data.
This is the code that I used before, which works (DataStream) :
SERVER:
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("HI FROM SERVER");
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
String input = in.readUTF();
for (ClientThread thatClient : server.getClients()){
DataOutputStream outputParticularClient = new DataOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeUTF(input + " GOT FROM SERVER");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket("localhost", portNumber);
DataInputStream in = new DataInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
String input = in.readUTF();
System.out.println(getUserName() + " > " + input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
And this is how I tried to perform the same idea with ObjectStream :
SERVER:
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
Message input;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("SERVER RETRIEVED NULL OBJECT");
}
for (ClientThread thatClient : server.getClients()){
ObjectOutputStream outputParticularClient = new ObjectOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeObject(input);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket(getHost(), portNumber);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
Message input = null;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("CLIENT RETRIEVED NULL OBJECT");
}
System.out.println("CLIENT " + input.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
I feel like it has something to do with this if statement if (in.available() > 0) but I cannot say precisely what's going on.
available() doesn't do what you may think it does and it is almost never useful in production code (and that's particularly true for ObjectInputStream). The reason you don't receive any data is in fact that in.available() always returns 0 as you already suspected.
As noted in the comments, the StreamCorruptedException is caused by writing to an existing ObjectInputStream that has already been written to using another instance of ObjectOutputStream. Cf. the answer StreamCorruptedException: invalid type code: AC for further explanation.
Here is some quick & dirty example code that has a server echoing the messages from two clients. It's not clean but it may give you an idea how to approach your problem:
public class SO56493162 {
private static final class Message implements Serializable {
private static final long serialVersionUID = 1L;
private static int cnt = 0;
private final int id;
public Message(int id) {
++cnt;
this.id = id;
}
public String toString() {
return "Msg from " + id + " : " + cnt;
}
}
private static final class Client implements Runnable {
private InetSocketAddress addr = null;
private int id = -1;
Client(InetSocketAddress addr, int id) {
this.addr = addr;
this.id = id;
}
public void run() {
int timeout = 3000;
Socket s = null;
try {
s = new Socket();
s.connect(addr, timeout);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println("Client " + id + " connected");
while (true) {
Thread.sleep(new Random().nextInt(2000));
Message hello = new Message(id);
oos.writeObject(hello);
oos.flush();
Message reply = (Message) ois.readObject();
System.out.println("Reply: " + reply.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (Exception ignore) {
}
}
}
}
private static final class Server implements Runnable {
private ServerSocket sock = null;
Server(ServerSocket sock) throws IOException {
this.sock = sock;
}
public void run() {
System.out.println("starting server");
try {
while (true) {
final Socket client = sock.accept();
System.out.println("connection accepted");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
while (!client.isClosed()) {
try {
Message input = (Message) ois.readObject();
oos.writeObject(input);
oos.flush();
} catch (EOFException eof) {
System.err.println("EOF!");
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException, InterruptedException {
final int port = 9876;
Thread ts = new Thread(new Runnable() {
#Override
public void run() {
try {
new Server(new ServerSocket(port)).run();
} catch (Exception e) {
e.printStackTrace();
}
}
});
ts.setDaemon(true);
ts.start();
InetSocketAddress addr = new InetSocketAddress("localhost", port);
for (int i = 0; i < 2; ++i) {
Client cl = new Client(addr, i);
Thread tc = new Thread(cl);
tc.setDaemon(true);
tc.start();
}
Thread.sleep(10000);
System.err.println("done");
}
}
Hi i have written a server program to receive ISO8583-93 version requests process them and send response.I will be receiving continuous requests.It works fine ,but if socket is idle when the next request comes, server is not reading.
Please find below code snippet
SERVER :
public class MBServ {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
String request_date = null;
String request_time = null;
try {
serverSocket = new ServerSocket(7777);
} catch (IOException e) {
System.err.println("Could not listen on port: 7777.");
System.exit(-1);
}
while (listening) {
new MBServT(serverSocket.accept()).start();
}
serverSocket.close();
}
}
THREAD:
public class MBServT extends Thread {
private Socket socket = null;
Logger log = Logger.getLogger(MBServT .class.getName());
public MBServT(Socket socket) throws FileNotFoundException, IOException {
super("MBServT");
this.socket = socket;
}
public void run() {
String inputLine = "";
String msgType = null;
int response = 12;
String outwardMsg = null;
BufferedReader buffReaderObj = null;
// String ip = "172.30.12.69";
String stanNo = "0";
boolean ISSUBFIELDPARSING = false;
GenericPackager packager;
try {
packager = new GenericPackager("basicparse.xml");
BufferedReader is = new BufferedReader(new InputStreamReader(socket
.getInputStream(), "ISO8859_1"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "ISO8859_1"));
String strBuf = null;
int length = 4;
char[] chrBuf = new char[length];
int cnt = 0;
while (true) {
socket.setKeepAlive(true);
int value = 0;
int ret = 0;
ret = is.read(chrBuf, 0, chrBuf.length);
if (-1 == ret)
{
log.error("nothing to read closing socket");
try{
socket.close();
}
catch(Exception e){
System.out.println("Error in socket.close: " +e.toString());
}
throw new Exception("Read Error: Socket closed");
}
strBuf = new String(chrBuf);
chrBuf = new char[Integer.parseInt(strBuf)];
is.read(chrBuf, 0, chrBuf.length);
strBuf = new String(chrBuf);
chrBuf = null;
chrBuf = new char[4];
value = 0;
/*writing response*/
Runnable respThread = new MBServRespT(writer, fieldList,
"threadname");
((Thread) respThread).start();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error::" + e.toString());
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It worked after we implemented set sockettimeout.
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.
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;
}
I'm trying to send over a small packet from one device to another,
My device ip is 192.168.1.59 which is the host,
Here is my server code
public class gameServer extends Thread{
/**
* Sets up a server for Android applciation
*/
private static final String TAG = "GameServer";
private DatagramSocket socket;
private int port = 50000;
private InetAddress local = null;
public gameServer( ) throws IOException
{
socket = new DatagramSocket( port );
Log.d(TAG, "Server was setup");
}
private String getLocalIPAddress()
{
try
{
for (Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); nis.hasMoreElements();)
{
NetworkInterface ni = nis.nextElement();
Log.v(TAG, "NetworkInterface = " + ni.getDisplayName());
for (Enumeration<InetAddress> ips = ni.getInetAddresses(); ips.hasMoreElements();)
{
InetAddress ip = ips.nextElement();
String s = ip.getHostAddress();
Log.v(TAG, "InetAddress = " + s);
if (!ip.isLoopbackAddress())
{
if(InetAddressUtils.isIPv4Address(s)) return s;
}
}
}
}
catch (SocketException e)
{
Log.e(TAG,"getLocalIPAddress()", e);
}
return null;
}
public void passClient( gameObject clientTemp )
{
}
#Override
public void run()
{
Log.d(TAG, "Ip address used:" + getLocalIPAddress() );
while( true )
{
//Send some data
try
{
local = InetAddress.getByName("127.0.0.1");
}
catch (UnknownHostException e2) {
e2.printStackTrace();
}
String msg = "hello there";
int msgLength = msg.length();
byte[] message = msg.getBytes();
DatagramPacket p = new DatagramPacket( message, msgLength, local, port );
try
{
socket.send( p );
}
catch (IOException e2)
{
Log.d(TAG, "Error with sending");
e2.printStackTrace();
}
}
}
}
Here is my client
public class gameClient extends Thread {
private static final String TAG = "gameClient";
private gameServer server;
private boolean rdyForPlay = false;
private ArrayList<gameObject> assets = new ArrayList();
private int ID = 0;
private maths cal = new maths();
public gameClient( boolean serverTag )
{
if( serverTag == true)
{
try
{
server = new gameServer();
server.run();
}
catch (IOException e)
{
Log.d(TAG, "Could not start server");
e.printStackTrace();
}
}
else
{
//DELETE!!!
//ONLY FOR TESTING
DatagramSocket socket = null;;
try
{
socket = new DatagramSocket( 50000 );
}
catch (SocketException e1)
{
e1.printStackTrace();
}
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket( buf, buf.length );
try
{
socket.receive( packet );
}
catch (IOException e)
{
Log.d(TAG, "Error with receiving data");
e.printStackTrace();
}
String data = new String( buf, 0, packet.getLength() );
Log.d(TAG, "Data received was :" + data);
}
}
public void sendTouchEvent(float xSet, float ySet)
{
}
#Override
public void run()
{
}
private void updateAssets()
{
}
}
When the code tries to receive a packet it just crashs on the socjet.receive( packet );
can anyone see any reason why?
Canvas
Your problem is that you have two try blocks. If the first one catches something socket stays null. So do something like that:
DatagramSocket socket = null;
try
{
socket = new DatagramSocket( 50000 );
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket( buf, buf.length );
socket.receive( packet );
}
catch (SocketException e1)
{
e1.printStackTrace();
}
catch (IOException e)
{
Log.d(TAG, "Error with receiving data");
e.printStackTrace();
}
Make sure to close() the socket onDestroy of your Activity!
Also consider AutoDiscovery instead of static IP's: AutoDiscovery