Client-Server UDP connection - java

I am trying to send Data from the server to client 1 bit at a time. Client should respond back with an ACK whenever it received a bit from the server.
What is currently happening is that when client sends the initial requests to the server, data is getting passed to the server. When server is sending the required data to the client, the data is getting looped back to itself and client is left in an indefinite waiting hang.
I've attached the code below for client and server. Please have a look at it and advise on where I am going wrong.
CLIENT SIDE:
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
class UDPClient extends Thread implements Runnable
{
DatagramSocket clientSocket;
InetAddress IPAddress;
public static void main(String args[]) throws Exception
{
try
{
UDPClient t1 = new UDPClient();
Thread t = new Thread(t1);
t.start();
}
catch (Exception e)
{
System.out.println("Error!");
}
}
public UDPClient() throws Exception
{
this.clientSocket = new DatagramSocket();
this.IPAddress = InetAddress.getByName("Localhost");
clientSocket.setSoTimeout(5000);
}
public void run()
{
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String m ="1001";
String checksum = "1111";
String checksumSend = "";
String sentence="";
String sentence1="";
String dataRequired="";
try
{
dataRequired = dataRequired.concat(m+":Data");
sendData = dataRequired.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
checksumSend = checksumSend.concat(checksum+":checksum");
sendData = checksumSend.getBytes();
DatagramPacket sendPacket2 = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket2);
Scanner in = new Scanner(System.in);
System.out.println("Enter the Window size: ");
int s = in.nextInt();
String WinSize="";
WinSize = WinSize.concat(s+":Windowsize");
sendData = WinSize.getBytes();
DatagramPacket sendPacket3 = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket3);
String finished="Finished";
sendData = finished.getBytes();
DatagramPacket sendPacket6 = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket6);
do
{
try
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
System.out.println("I am getting executed");
clientSocket.receive(receivePacket); //After this step, nothing gets executed
sentence = new String(receivePacket.getData(),0,receivePacket.getLength());
System.out.println("Received from Server: " + sentence);
if(receivePacket != null)
sentence1 = "ACK";
sendData = sentence1.getBytes();
DatagramPacket sendPacket4 =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket4);
}
catch (SocketTimeoutException a)
{
System.out.println("Timed out!");
}
}while(sentence!=null);
}
catch (IOException e)
{
System.err.println(e);
}
finally
{
clientSocket.close();
}
}
}
SERVER SIDE:
import java.io.IOException;
import java.net.*;
public class UDPServer extends Thread implements Runnable
{
DatagramSocket serverSocket;
public static void main(String args[]) throws Exception
{
try
{
UDPServer t1 = new UDPServer();
Thread t = new Thread(t1);
t.start();
}
catch (Exception e)
{
System.out.println("Error!");
}
}
public UDPServer() throws Exception
{
this.serverSocket = new DatagramSocket(9876);
}
public void run()
{
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
String checksum="";
String Data = "";
String WinSize = "";
String carry = "0";
String output="";
String n,o;
String output1;
String sentence1="";
int i,j=0;
while(true)
{
String sentence="";
try
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
InetAddress IPAddress = receivePacket.getAddress();
sentence = new String( receivePacket.getData(),0,receivePacket.getLength());
if(sentence.contains("checksum"))
{
int len = sentence.length();
for(i=0;i<len;i++)
{
if(sentence.charAt(i)==':')
{
checksum = sentence.substring(0,i);
}
}
System.out.println("Checksum as specified by client is: " + checksum);
}
else if(sentence.contains("Data"))
{
int len = sentence.length();
for(i=0;i<len;i++)
{
if(sentence.charAt(i)==':')
{
Data = sentence.substring(0,i);
}
}
System.out.println("Data requested by client is: " + Data);
}
else if(sentence.contains("Windowsize"))
{
int len = sentence.length();
for(i=0;i<len;i++)
{
if(sentence.charAt(i)==':')
{
WinSize = sentence.substring(0,i);
}
}
System.out.println("Window Size is: " + WinSize);
}
else if(sentence.contains("Finished"))
{
output1 = checksumAdd(carry,Data,checksum);
output = reverse(output1);
System.out.println("Checksum Addition before complementing digits = "+output);
output = complement(output);
output = reverse(output);
System.out.println("Checksum Addition after complementing digits = "+output);
int WindowSize = Integer.parseInt(WinSize);
int strlen = Data.length();
do
{
for(i=j;i<(WindowSize+j);i++)
{
if(i!=strlen)
{
String send = "";
n = Data.substring(i,i+1);
System.out.println("Value of n is: "+n);
send = send.concat(n+":");
o = output.substring(i,i+1);
System.out.println("Value of o is: "+o);
send = send.concat(o);
sendData = send.getBytes();
DatagramPacket sendPacket1 = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
serverSocket.send(sendPacket1);
}
else
break;
}
j+=WindowSize;
DatagramPacket receivePacket2 = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket2);
sentence1 = new String( receivePacket2.getData(),0,receivePacket2.getLength());
System.out.println("sentence 1 is: "+sentence1); //To be removed. Used for testing purposes
}while(i!=strlen);
}
}
catch (IOException e)
{
System.err.println(e);
}
}
}
public static String complement(String output) {
String temp="";
int len = output.length();
for(int i=len;i>0;i--)
{
String t = output.substring(i-1,i);
if(t.equals("0"))
temp = temp.concat("1");
else if(t.equals("1"))
temp = temp.concat("0");
}
return temp;
}
public static String reverse(String output)
{
String temp="";
int len = output.length();
for(int i=len;i>0;i--)
{
String t = output.substring(i-1,i);
temp = temp.concat(t);
}
return temp;
}
public static String checksumAdd(String carry, String Data,String checksum)
{
int strlen = Data.length();
int flag=0;
String output="";
String output2="";
String n,che;
String sum = null;
for(int i=strlen;i>0;i--)
{
n=Data.substring(i-1,i);
che = checksum.substring(i-1,i);
if(n.equals("0") && che.equals("0") && carry.equals("0"))
{
sum = "0";
carry = "0";
}
else if(n.equals("0") && che.equals("0") && carry.equals("1"))
{
sum = "1";
carry = "0";
}
else if(n.equals("0") && che.equals("1") && carry.equals("0"))
{
sum = "1";
carry = "0";
}
else if(n.equals("0") && che.equals("1") && carry.equals("1"))
{
sum = "0";
carry = "1";
}
else if(n.equals("1") && che.equals("0") && carry.equals("0"))
{
sum = "1";
carry = "0";
}
else if(n.equals("1") && che.equals("0") && carry.equals("1"))
{
sum = "0";
carry = "1";
}
else if(n.equals("1") && che.equals("1") && carry.equals("0"))
{
sum = "0";
carry = "1";
}
else if(n.equals("1") && che.equals("1") && carry.equals("1"))
{
sum = "1";
carry = "1";
}
output = output.concat(sum);
}
if(carry.equals("1"))
{
n = output.substring(0,1);
if(n.equals("0"))
{
sum = "1";
carry = "0";
}
else if(n.equals("1"))
{
sum = "0";
carry = "1";
}
output2 = output2.concat(sum);
for(int i=strlen-1;i>0;i--)
{
n=Data.substring(i-1,i);
if(n.equals("0") && carry.equals("0"))
{
sum = "0";
carry = "0";
}
else if(n.equals("0") && carry.equals("1"))
{
sum = "1";
carry = "0";
}
else if(n.equals("1") && carry.equals("0"))
{
sum = "1";
carry = "0";
}
else if(n.equals("1") && carry.equals("1"))
{
sum = "0";
carry = "1";
}
output2 = output2.concat(sum);
}
flag = 1;
}
if (flag==1)
return output2;
return output;
}
}

If your client doesn't receive a response from your server, it's probably because the server doesn't send a response.
serverSocket.send(sendPacket1);
is only called if(i!=strlen).
Have you tried to output some text in the console inside the if block to see if/when you enter that loop?

Related

Java: send/receive data through TCP and receive image from UDP

I'm working in a code that come from C# and I'm trying to traduce it in java.
Basically in first step I send and receive some data-command to an IP camera through TCP (this is done) and in second step I have to receive the image through UDP. The problem is with second step: receive image from UDP.
I try every code in internet but no one work.
The originally code in C# is this:
*Example to server connection in C#
Socket _ServerUdp = null;
Socket _ServerTcpIp = null;
IPEndPoint _EndpointUdp = null;
TcpClient _ClientUdp;
/// <summary>
/// Connect the socket
/// <summary>
public bool Connect(string IpAddr)
{
if (!_VideoPortConnect(IpAddr, 8501))
return false;
if (!_CommandPortConnect(IpAddr, 8500))
return false;
return true;
}
/// <summary>
/// Udp Connect
/// </summary>
bool _VideoPortConnect(string IpAddr, int VideoPort)
{
try
{
_ServerUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_EndpointUdp = new IPEndPoint(IPAddress.Parse(IpAddr), VideoPort);
_ClientUdp = new TcpClient();
_ClientUdp.Connect(_EndpointUdp);
return true;
}
catch { return false; }
}
/// <summary>
/// Tcp Ip Connect
/// </summary>
bool _CommandPortConnect(string IpAddr, int CommandPort)
{
_ServerTcpIp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint _RemoteEndPoint = new IPEndPoint(IPAddress.Parse(IpAddr), CommandPort);
_ServerTcpIp.ReceiveTimeout = 5000;
_ServerTcpIp.SendTimeout = 5000;
try
{
_ServerTcpIp.Connect(_RemoteEndPoint);
return true;
}
catch { return false; }
*}*
Example for send command and receive image
The command will be send by TCP/IP.
byte[] DataReceived = new byte[20000];
/// <summary>
/// Send Command Bar Code Reader
/// </summary>
/// <returns></returns>
bool SendCommand()
{
byte[] _Send = new byte[3];
_Send[0]= 20; //CMD BAR CODE READER
_Send[1] = 2; //EXT CMD GET DATA
_Send[2] = 2; //SEND IMAGE
if (!SendEth(_Send, 3))
return false;
int _Ndati = ReadEth();
if (_Ndati == -1)
return false;
if (DataReceived[4] != 20)
return false;
GetImage();
}
/// <summary>
/// Send Data
/// </summary>
/// <param name="_Val"></param>
/// <param name="_Len"></param>
bool SendEth(byte[] _Val, Int32 _Len)
{
try
{
byte[] _Send = new byte[_Len + 4];
int _Value = _Len;
Array.Copy(_Val, 0, _Send, 4, _Len);
_Send[3] = (byte)_Value;
_Value <<= 8;
_Send[2] = (byte)_Value;
_Value <<= 8;
_Send[1] = (byte)_Value;
_Value <<= 8;
_Send[0] = (byte)_Value;
_ServerTcpIp.Send(_Send, _Len + 4, SocketFlags.None);
}
catch { return false; }
return true;
}
/// <summary>
/// Read Data from Ethernet
/// </summary>
/// <param name="LenDati"></param>
/// <returns>array dati</returns>
internal int ReadEth()
{
int _Ndati;
try
{
_Ndati = _ServerTcpIp.Receive(DataReceived, SocketFlags.None);
DataPointer =0;
int _Len = GetInt();
if(_Len!=_Ndati-4)
{
int _Diff = (_Ndati - 4) - _Len;
byte[] BuffRx = new byte[_Diff];
int _NrDati = 0;
int _PuntRx = _Ndati;
while (_PuntRx < _Diff)
{
_NrDati = _ServerTcpIp.Receive(BuffRx, _Diff, SocketFlags.None);
for (int n = 0; n < _NrDati; n++)
DataReceived[_PuntRx++] = BuffRx[n];
}
}
return _Ndati;
}
catch { return -1; }
}
/// <summary>
/// Get Image
/// </summary>
/// <returns></returns>
internal ImageSource GetImage()
{
//get image
NetworkStream _Stream = _ClientUdp.GetStream();
byte[] _Data = (byte[])_Formatter.Deserialize(_Stream);
MemoryStream _ImgStream = new MemoryStream(_Data);
ImageSource _Image = BitmapFrame.Create(_ImgStream, BitmapCreateOptions.None,
BitmapCacheOption.OnLoad);
return _Image;
}
My JAVA code:
public class TFinale {
static byte[] DataReceived = new byte[20000];
public static void main(String[] args) throws Exception {
String[] args8500 = new String[2];
args8500[0] = "10.0.0.123";
args8500[1] = "8500";
int port8500 = Integer.parseInt(args8500[1]);
String[] args8501 = new String[2];
args8501[0] = "10.0.0.123";
args8501[1] = "8501";
int port8501 = Integer.parseInt(args8501[1]);
Socket clientSocket8501 = TFinale.createSocket(args8501[0], port8501);
if (clientSocket8501 == null) {
System.err.println("Unable to create socket to " + args8501[0] + ":" + port8501 + ".");
System.exit(1);
}
Socket clientSocket8500 = TFinale.createSocket(args8500[0], port8500);
if (clientSocket8500 == null) {
System.err.println("Unable to create socket to " + args8500[0] + ":" + port8500 + ".");
System.exit(1);
}
byte[] _Send = new byte[3];
_Send[0] = 22; //CMD BAR CODE READER
_Send[1] = 2; //EXT CMD GET DATA
_Send[2] = 2; //SEND IMAGE
int _Len1 = 3;
byte[] SendEth1 = SendEth(_Send, _Len1);
DataOutputStream serverOut = null;
try {
serverOut = new DataOutputStream(clientSocket8500.getOutputStream());
serverOut.write(SendEth1, 0, 7);
System.out.println("serverOut writed!");
} catch (IOException ex) {
Logger.getLogger(TFinale.class.getName()).log(Level.SEVERE, null, ex);
}
DataInputStream in = null;
try {
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
in = new DataInputStream(clientSocket8500.getInputStream());
int bytesRead = 0;
int f = 0;
//System.out.println("Please type 8500 clientSocket......");
for (f = 0; f < 7; f++) {
messageByte[f] = in.readByte();
System.out.println("messageByte 8500[" + f + "] " + messageByte[f]);
}
ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, f);
int bytesToRead = byteBuffer.getShort();
System.out.println("About to read " + bytesToRead + " octets");
} catch (IOException ex) {
Logger.getLogger(TCPClient1.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
Logger.getLogger(TCPClient1.class.getName()).log(Level.SEVERE, null, ex);
}
}
timeDelay(1000);
try {
serverOut.close();
System.out.println("serverOut closed!");
in.close();
System.out.println("in closed!");
clientSocket8501.close();
System.out.println("clientSocket8501 closed!");
clientSocket8500.close();
System.out.println("clientSocket8500 closed!");
} catch (IOException ex) {
System.out.println("error:" + ex);
}
}
private static Socket createSocket(final String hostname, final int port) {
try {
Socket clientSocket = new Socket(hostname, port);
System.out.println(hostname + ":" + port + " socket created!");
return clientSocket;
} catch (UnknownHostException e) {
System.err.println(" " + hostname + " cannot be resolved as a network host.");
return null;
} catch (IOException e) {
System.err
.println("An exception occurred while communicating with the TCPServer: "
+ e.getMessage());
e.printStackTrace();
return null;
}
}
private static void timeDelay(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
}
}
private static byte[] SendEth(byte[] _Val, int _Len) {
byte[] _Send = new byte[_Len + 4];
int _Value = _Len;
System.arraycopy(_Val, 0, _Send, 4, _Len);
//Array.Copy(_Val, 0, _Send, 4, _Len);
_Send[3] = (byte) _Value;
_Value <<= 8;
_Send[2] = (byte) _Value;
_Value <<= 8;
_Send[1] = (byte) _Value;
_Value <<= 8;
_Send[0] = (byte) _Value;
return _Send;
}
}
Thanks everybody can help me!
#Federico111, you should use java.net.DatagramSocket instead of Socket to work with UDP.

Why doesn't a socket send the last message unless there is a delay before it?

Alright so I am looking at this piece of code that is supposed to get an array of bytes which represents an image and send it piece by piece to a server. The server needs to be told when the image transmission is done, this ending message is "CLOSE". Everything works fine but unless I uncomment Thread.sleep the end message isn't sent. Also the delay needs to be quite big for some reason, 100 ms for example doesn't work. If anyone could provide an explanation for this behaviour I would be grateful since I don't have a very good understanding of java.
private class NetTask extends AsyncTask<Void, Void, Void>
{
private String ip;
private byte[] to_send;
public NetTask(String ip, byte[] to_send)
{
this.ip = ip;
this.to_send = to_send;
}
#Override
protected Void doInBackground(Void...params)
{
try {
Log.i(dTag, "" + to_send.length);
Socket sck = new Socket(ip, 1234);
DataOutputStream dOut = new DataOutputStream(sck.getOutputStream());
dOut.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(to_send.length).array());
Log.d(dTag, "" + to_send.length);
int x = 500;
int len = to_send.length;
for (int i = 0; i < len - x + 1; i += x)
dOut.write(Arrays.copyOfRange(to_send, i, i + x));
if (len % x != 0)
dOut.write(Arrays.copyOfRange(to_send, len - len % x, len));
/*try {
Thread.sleep(1000);
}
catch (Exception ex) {
Log.d(dTag, "thread sleep error");
}*/
dOut.write("CLOSE".getBytes());
dOut.flush();
dOut.close();
sck.close();
}
catch (IOException ex) {
Log.d(dTag, ex.getMessage());
}
return null;
}
}
The server is in c#, here is the code:
while (ok)
{
sck.Listen(1000);
Socket accepted = sck.Accept();
buffer = new byte[accepted.SendBufferSize];
int bytesRead = -1;
bool reading = true;
int im_size = -1;
int index = 0;
byte[] image = null;
while (reading)
{
bytesRead = accepted.Receive(buffer);
if (bytesRead == 5)
Console.WriteLine(bytesRead);
string strData = "YADA";
byte[] formatted = new byte[bytesRead];
if (bytesRead == 5)
{
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = buffer[i];
}
strData = Encoding.ASCII.GetString(formatted);
}
if (strData == "CLOSE")
{
Console.WriteLine("GOT CLOSE MESSAGE");
Image im = Image.FromStream(new MemoryStream(image));
im.Save(#"D:\im1.bmp");
}
else
{
if (im_size == -1)
{
im_size = BitConverter.ToInt32(buffer, 0);
image = new byte[im_size];
Console.WriteLine(im_size);
}
else
{
for (int i = 0; i < bytesRead && index < im_size; i++)
{
image[index++] = buffer[i];
}
}
}
}
accepted.Close();
}

TCP sockets returning strange thing in Java

I have socket application that i use for communication with a device.
When i open socket i can read status outputs from the machine.
Machine sends some data which is separated by comma ',' and i need to parse only numbers.
The problem is when i parse the data i recieve numbers but i also recieve "empty" strings.
Here is my code:
void startListenForTCP(String ipaddress) {
Thread TCPListenerThread;
TCPListenerThread = new Thread(new Runnable() {
#Override
public void run() {
Boolean run = true;
String serverMessage = null;
InetAddress serverAddr = null;
BufferedWriter out = null;
int redni = 0;
try {
Socket clientSocket = new Socket(ipaddress, 7420);
try {
mc.pushNumbers("Connection initiated... waiting for outputs!"
+ "\n");
char[] buffer = new char[2];
int charsRead = 0;
out =
new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((charsRead = in.read(buffer)) != -1) {
String message = new String(buffer).substring(0, charsRead);
if (message.equals("I,")) {
mc.pushNumbers("\n");
} else {
String m = message;
m = m.replaceAll("[^\\d.]", "");
String stabilo = m;
int length = stabilo.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = stabilo.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("Result:" + m);
}
}
} catch (UnknownHostException e) {
mc.pushNumbers("Unknown host..." + "\n");
} catch (IOException e) {
mc.pushNumbers("IO Error..." + "\n");
} finally {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
mc.pushNumbers("Connection refused by machine..." + "\n");
}
}
});
TCPListenerThread.start();
}
And the System.out.println(); returns this:
Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:26Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:13
Result:Result:Result:Result:Result:Result:Result:Result:Result:
I just don't know why I can't parse only numbers, there is probably something that machine sends and it isn't parsed by m = m.replaceAll("[^\\d.]", "");
You're building your String incorrectly. It should be:
String message = new String(buffer, 0, bytesRead);
where 'bytesRead' is the count returned by the read() method. It's a byte count, not a char count.

"java.net.SocketException: Connection reset by peer: socket write error" How can I solve it [duplicate]

This question already has answers here:
java.net.SocketException: Connection reset
(14 answers)
Closed 12 months ago.
I have a problem with my senior project. My objective is to read and modify HTTP response packet. I have a problem about java.net.SocketException. Could you help me, please?
Exception at Responsethread
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113)
at java.net.SocketOutputStream.write(SocketOutputStream.java:147)
at helper.ResponseThread.run(ResponseThread.java:163)
BUILD STOPPED (total time: 4 minutes 3 seconds)
Here is my code
Helper.java
package helper;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Helper {
public void proc() {
try {
ServerSocket servsock = new ServerSocket(80);
String hostname="www.hungeng.besaba.com";
InetAddress ip=InetAddress.getByName(hostname);
//int serverPort=3456;
//Socket clientSocket =new Socket(ip,serverPort);
//String ipAddr="31.170.164.70"; //http://hungeng.besaba.com/
while (true) {
Socket sockC = servsock.accept();
//get input stream of the Socket(sockC) from Client
InputStream inC = sockC.getInputStream();
//get output stream of the Socket(sockC) to Client
OutputStream outC = sockC.getOutputStream();
//Connect to the specified server(ipAddr) at the 80 port.
Socket sockS = new Socket(ip, 80);
//get input stream of the Socket(sockS) from server(ipAddr)
InputStream inS = sockS.getInputStream();
//get output stream of the Socket(sockS) to server(ipAddr)
OutputStream outS = sockS.getOutputStream();
//Create Thread for sending The Request Message from Client
RequestThread request = new RequestThread();
//Create Thread for sending The Response Message to Client
ResponseThread response = new ResponseThread();
// match a Request Thread with a Response Thread
request.server = response;
response.client = request;
request.is = inC;
request.os = outC;
response.is = inS;
response.os = outS;
request.start();
response.start();
}
} catch (Exception x) {
x.printStackTrace();
}
}
public static void main(String[] args) {
// TODO code application logic here
new Helper().proc();
}
}
RequestThread.java
package helper;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class RequestThread extends Thread {
InputStream is;
OutputStream os;
ResponseThread server;
byte[] buf = new byte[1024];
int bytesRead;
public void run() {
try {
int i=0;
while ((bytesRead = is.read(buf)) !=-1) {
server.os.write(buf,0,bytesRead);
server.os.flush();
}
} catch (Exception x) {
x.printStackTrace();
}
}
}
ResponseThread.java
package helper;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class ResponseThread extends Thread {
int num;
String content = "";
InputStream is;
OutputStream os;
RequestThread client;
byte[] buf = new byte[20000];
int bytesRead = 0;
String endMark = "\r\n\r\n";
public void run() {
try {
String msg = "";
while ((bytesRead = is.read(buf)) != -1) {
msg += new String(buf, 0, bytesRead);
// System.out.println("message");
//System.out.println(msg);
// System.out.println("---------");
//client.os.write(buf, 0, bytesRead);
int eHeader = msg.indexOf("\r\n\r\n");
String header = msg.substring(0, eHeader + "\r\n\r\n".length());
// System.out.println("header");
//System.out.println(header);
//System.out.println("-----------");
int sConLength = header.indexOf("Content-Length: ");
if (sConLength != -1) {
//have content length
String temp = header.substring(sConLength);
int eConLength = temp.indexOf("\r\n");
int cl = Integer.parseInt(temp.substring("Content-Length: ".length(), eConLength));
String uConlen = header.substring(0, sConLength + "Content-Length: ".length());
System.out.println("uconlen ");
System.out.println(uConlen);
System.out.println("--------");
String lConlen = temp.substring(eConLength + "\r\n".length());
System.out.println("lconlen ");
System.out.println(lConlen);
System.out.println("-----------------");
int sHtml = msg.toLowerCase().indexOf("<html>");
int eHtml = msg.toLowerCase().indexOf("</html>");
if ((sHtml != -1) && (eHtml != -1)) {
//has Html content
System.out.println(":::Have Html content:::");
int sForm = msg.toLowerCase().indexOf("<form");
int eForm = msg.toLowerCase().indexOf("</form>");
if ((sForm != -1) && (eForm != -1)) {
//have form
System.out.println(":::Have form:::");
String form = msg.substring(sForm, eForm + "</form>".length());
String uForm = msg.substring(eHeader + "\r\n\r\n".length(), sForm);
String lForm = msg.substring(eForm + "</form>".length());
String p = "<p id=\"demo\"></p>";
String bt = "<button type=\"button\" onclick=\"fill_in(name)\">Fill In</button>\n";
String[] data = {"Natta santawalim", "110033333333", "adressssss"};
String sc = "<script>\n ";
sc += "function fill_in(name) \n";
sc += "{\n";
sc += "document.getElementById(\"txtUsername\").value=\'";
sc += data[0];
sc += "\'; \n";
sc += "document.getElementById(\"txtPassword\").value=\'";
sc += data[1];
sc += "\'; \n";
sc += "document.getElementById(\"txtName\").value=\'";
sc += data[2];
sc += "\'; \n";
sc += "}\n";
sc += "</script>\n";
// client.os.write(result.getBytes());
cl += bt.length() + p.length() + sc.length();
client.os.write(uConlen.getBytes());
String l = Integer.toString(cl) + "\r\n";
client.os.write(l.getBytes());
client.os.write(lConlen.getBytes());
client.os.write(uForm.getBytes());
client.os.write(form.getBytes());
client.os.write(bt.getBytes());
client.os.write(sc.getBytes());
client.os.write(p.getBytes());
client.os.write(lForm.getBytes());
// System.out.println("byte "+);
//System.out.println("numofsent byr"+s);
} else {
//don't have form
System.out.println(":::Dont Have form:::");
//client.os.write(buf, 0, bytesRead);
String packet = msg.substring(eHeader + "\r\n\r\n".length());
client.os.write(header.getBytes());
client.os.write(packet.getBytes());
client.os.flush();
}
} else {
// don't have Html content
System.out.println(":::Dont Have Html content:::");
client.os.write(buf, 0, bytesRead);
//client.os.flush();
// num+=bytesRead;
//System.out.println("num "+num);
}
} else {
//don't have content length,transfer-encoding: chunk
System.out.println("chunk");
//client.os.write(buf, 0, bytesRead);
// System.out.println("message");
//System.out.println(msg);
int fChunk = header.indexOf("Transfer-Encoding: chunked");
// String m = msg.substring(eHeader + "\r\n\r\n".length());
if (fChunk != -1) {
//chunk
int sHtml = msg.toLowerCase().indexOf("<html>");
int eHtml = msg.toLowerCase().indexOf("</html>");
if ((sHtml != -1) && (eHtml != -1)) {
//have html
String packet = msg.substring(eHeader + "\r\n\r\n".length());
String[] chunkPt = packet.split("\r\n");
// System.out.println("=====chunk=========== ");
client.os.write(header.getBytes());
for (int i = 0; i < (chunkPt.length - 1); i++) {
int fForm=chunkPt[i].toLowerCase().indexOf("</form>");
if(fForm!=-1){
String bt = "<button type=\"button\" onclick=\"fill_in(name)\">Fill In</button>\n";
int btSizeDec=bt.length();
int cSizeDec=Integer.parseInt(chunkPt[i-1],16);
int totalSizeDec=btSizeDec+cSizeDec;
String totalSizeHex=Integer.toHexString(totalSizeDec);
String h=chunkPt[i].substring(0,fForm);
String t=chunkPt[i].substring(fForm);
chunkPt[i]=h+bt+t;
chunkPt[i-1]=totalSizeHex;
System.out.println("chunkEmbedded");
System.out.println(chunkPt[i]);
}
client.os.write((chunkPt[i]+"\r\n").getBytes());//Error occured here
}
client.os.write((chunkPt[chunkPt.length - 1] + "\r\n\r\n").getBytes());
} else {
System.out.println("dont hav html");
//dont have html
}
} else {
//dont chunk
System.out.println("dont chunk");
}
}
}
client.os.flush();
} catch (Exception x) {
x.printStackTrace();
}
}
}
This exception usually means that you have written to an connection that had already been loses by the peer. In other words, an application protocol error. There are other causes, but this is the most common.

how to get UDP connection in infinite loop?

I am trying to write a program to implement the distance vector algorithm.
So I need the node to act as both the server and the client.
Basically I am using UDP protocol to send and receive messages. I am trying to listen for message from neighbouring nodes while sending the node's distance vector out every 5 seconds.
My main problem is that I want the stop listening for message so that I can broadcast my distance vector. I tried using setSoTimeout but then I get all sorts of exception that I dont know how to handle. and I am not too sure how to "reopen" the socket again to either wait for the message again or move on to broadcasting the message....
Can anybody please point me to the right direction?
My code is as follows:
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class dv_routing {
public static void main(String[] args) throws Exception {
//initialise variables to default value
int NodeID = 0;
int NodePort = 6000;
String configFile = "A.txt";
int numNbr = 0; // zero neighbour
double[] CostList = new double[10]; //Self cost list
Arrays.fill(CostList, Double.POSITIVE_INFINITY);
int[] ViaList = new int[10]; //Self cost list
Arrays.fill(ViaList, 9999);
double[] Cost = new double[10]; //Inf cost array for Nbr initialization
Arrays.fill(Cost, Double.POSITIVE_INFINITY);
Neighbour Nbr = new Neighbour(); //create Nbr
boolean ischanged = false;
//read user input
if (args.length >= 3) {
System.out.println("i'm here!");
String tmp = args[0];
char tmpchar = tmp.charAt(0);
NodeID = ((int)tmpchar - 65);
NodePort = Integer.parseInt(args[1]);
configFile = args[2];
CostList[NodeID] = 0;
System.out.println(NodeID);
System.out.println(NodePort);
System.out.println(configFile);
//poison reverse
if (args.length <= 4) {
// TODO: poison reverse
}
else
System.out.println("Incorrect Input Format! Please try again!");
}
//reading config file for neighbour data
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(configFile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//capture the number neighbours
if ((strLine = br.readLine()) != null){
numNbr = Integer.parseInt(strLine);
System.out.println (numNbr);
}
int elementcnt = 0;
while ((strLine = br.readLine()) != null) {
//separate data
String[] temp = strLine.split(" ");
//get neighbour Node ID
char tmpchar = temp[0].trim().charAt(0);
int ID = (int)(tmpchar - 65);
//NbrIDList.add(new NbrID((int)tmpchar - 65));
//get neighbour cost
CostList[ID] = Double.parseDouble(temp[1].trim());
ViaList[ID] = ID;
//get neighbour port number
int Port = Integer.parseInt(temp[2].trim());
//create entry for neighbour
Nbr.addData(ID, Port);
Nbr.addCost(Cost);
//debugging
//System.out.println((char)(Nbr.getID(elementcnt)+65));
//System.out.println(Nbr.getPort(elementcnt));
//System.out.println(Nbr.getCost(elementcnt)[0]);
elementcnt++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
//set timers
long now = System.currentTimeMillis();
long end = now + 50 * 1000;
long broadcast = now + 1 * 1000;
long current = System.currentTimeMillis();
while(current < end) {
System.out.println("in first layer");
//open UDP socket for listening..
DatagramSocket nodeSocket = new DatagramSocket(NodePort);
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
//braodcast...
String OutMsg = CostList[0]+"\t"+CostList[1]+"\t"+CostList[2]+"\t"+CostList[3]+"\t"+CostList[4]+"\t"+CostList[5]+"\t"+CostList[6]+"\t"+CostList[7]+"\t"+CostList[8]+"\t"+CostList[9];
sendData = OutMsg.getBytes();
for (int i = 0; i < numNbr; i++){
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, Nbr.getPort(i));
nodeSocket.send(sendPacket);
}
nodeSocket.setSoTimeout(1000);
while(current < broadcast){
if (nodeSocket.isClosed()){
nodeSocket = new DatagramSocket(NodePort);
}
System.out.println("in receiving layer");
current = System.currentTimeMillis();
ischanged = false;
//get MSG
// Msg format.. "cost1"\t"cost2"\t"cost3"...
try{DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
nodeSocket.receive(receivePacket);
System.out.println("we got here");
String Msg = new String( receivePacket.getData());
System.out.println("RECEIVED: " + Msg);
int NbrPort = receivePacket.getPort();
System.out.println("From: " + NbrPort);
//process the MSG
String[] tmpstr = Msg.split("\t");
for (int i = 0; i<10; i++) {
Cost[i] = Double.parseDouble(tmpstr[i]);
}
int Idx = Nbr.indexOfPort(NbrPort);
System.out.println("From: " + NbrPort);
Nbr.updateCost(Idx, Cost);
//compare cost and update list
for (int i = 0; i<10;i++) {
double NbrNodeCost = (Nbr.getCost(Idx)[i] + CostList[Nbr.getID(Idx)]);
if (!(Double.isInfinite(NbrNodeCost)) && CostList[i] > NbrNodeCost) {
CostList[i] = NbrNodeCost;
ViaList[i] = Nbr.getID(Idx);
ischanged = true;
}
}
System.out.println("Is the list changed? " + ischanged);
System.out.println(CostList[0]+" "+CostList[1]+" "+CostList[2]+" "+CostList[3]+" "+CostList[4]+" "+CostList[5]+" "+CostList[6]+" "+CostList[7]+" "+CostList[8]+" "+CostList[9]);
System.out.println(ViaList[0]+" "+ViaList[1]+" "+ViaList[2]+" "+ViaList[3]+" "+ViaList[4]+" "+ViaList[5]+" "+ViaList[6]+" "+ViaList[7]+" "+ViaList[8]+" "+ViaList[9]);
}catch (SocketTimeoutException e) {
//System.err.println("Caught SocketException: " + e.getMessage());
System.out.println("Timeout reached!!! " + e);
nodeSocket.close();
nodeSocket = new DatagramSocket(NodePort);
current = System.currentTimeMillis();
}
catch (SocketException e1){
System.out.println("Socket closed " + e1);
}
}
//Broadcast List
System.out.println("broadcast");
broadcast = current + 1 * 1000;
current = System.currentTimeMillis();
if (ischanged) {
end = current + 10 * 1000;
}
//braodcast...
OutMsg = CostList[0]+"\t"+CostList[1]+"\t"+CostList[2]+"\t"+CostList[3]+"\t"+CostList[4]+"\t"+CostList[5]+"\t"+CostList[6]+"\t"+CostList[7]+"\t"+CostList[8]+"\t"+CostList[9];
sendData = OutMsg.getBytes();
for (int i = 0; i < numNbr; i++){
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, Nbr.getPort(i));
nodeSocket.send(sendPacket);
}
}
//Print List
//Shortest path to node B: the next hop is C and the cost is 5
for(int i = 0; i <10; i++) {
if(ViaList[i] != 9999){
System.out.println("Shortest path to node "+(char)(i+65)+": the next hop is "+(char)(ViaList[i])+" and the cost is "+CostList[i]);
}
}
System.out.println("end");
}
}
class Neighbour {
public Neighbour(){
NbrIDList = new ArrayList<Integer>();
NbrPortList = new ArrayList<Integer>();
NbrCostList = new ArrayList<double[]>();
}
public void addData(int ID, int Port){
NbrIDList.add(ID);
NbrPortList.add(Port);
}
public void addCost(double[] Cost){
NbrCostList.add(Cost);
}
public int getID(int idx){
return (Integer) NbrIDList.get(idx);
}
public int getPort(int idx){
return (Integer) NbrPortList.get(idx);
}
public int indexOfPort(int Port){
return (Integer) NbrPortList.indexOf(Port);
}
public double[] getCost(int idx){
return (double[]) NbrCostList.get(idx);
}
public void updateCost(int idx, double[] Cost){
NbrCostList.set(idx,Cost);
}
private ArrayList<Integer> NbrIDList;
private ArrayList<Integer> NbrPortList;
private ArrayList<double[]> NbrCostList;
}
Networking is almost 99,8% threading. To solve your problem, you can create one thread to receiving messages and second one for sending message every 5 seconds.
There was a lot of questions about this:
Java: Multithreading & UDP Socket Programming
How can I implement a threaded UDP based server in Java?
java2s is also good:
Server
Client

Categories

Resources