how to get UDP connection in infinite loop? - java

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

Related

Cant send the data from my "sender.java" to my "receiver.java". (Java Socket Programming)

I am having issues with my two java programs communicating with each other. The problem is that the "receiver.java" program that acts as the server cannot run / start or receive data from the "sender.java" program. The sender program works and runs fine though on port :4444. I am getting Java socket connection error so it has something to do with connection.
FINAL UPDATE EDIT*****: It works fine now, I fixed the first problem by changing the ports to match. (4444). And I passed the receiver to connect through (IP,4444) NOT (localhost,4444) so I ran "sender.java" on my local IP address which is 127...*:4444 and "receiver.java" on (localhost:4444) and they connected and the receiver received the checksum data I inputed. Thanks all!
Check_Sum_Sender.java
// Java code for Checksum_Sender
package checksum_sender;
import java.io.*;
import java.net.*;
import java.util.*;
public class Checksum_Sender
{
// Setting maximum data length
private int MAX = 100;
// initialize socket and I/O streams
private Socket socket = null;
private ServerSocket servsock = null;
private DataInputStream dis = null;
private DataOutputStream dos = null;
public Checksum_Sender(int port) throws IOException
{
servsock = new ServerSocket(port);
// Used to block until a client connects to the server
socket = servsock.accept();
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
while (true)
{
int i, l, sum = 0, nob;
Scanner sc = new Scanner(System.in);
System.out.println("Enter data length");
l = sc.nextInt();
// Array to hold the data being entered
int data[] = new int[MAX];
// Array to hold the complement of each data
int c_data[] = new int[MAX];
System.out.println("Enter data to send");
for (i = 0; i < l; i++)
{
data[i] = sc.nextInt();
// Complementing the entered data
// Here we find the number of bits required to represent
// the data, like say 8 requires 1000, i.e 4 bits
nob = (int)(Math.floor(Math.log(data[i]) / Math.log(2))) + 1;
// Here we do a XOR of the data with the number 2^n -1,
// where n is the nob calculated in previous step
c_data[i] = ((1 << nob) - 1) ^ data[i];
// Adding the complemented data and storing in sum
sum += c_data[i];
}
// The sum(i.e checksum) is also sent along with the data
data[i] = sum;
l += 1;
System.out.println("Checksum Calculated is : " + sum);
System.out.println("Data being sent along with Checkum.....");
// Sends the data length to receiver
dos.writeInt(l);
// Sends the data one by one to receiver
for (int j = 0; j < l; j++)
dos.writeInt(data[j]);
// Displaying appropriate message depending on feedback received
if (dis.readUTF().equals("success"))
{
System.out.println("Thanks for the feedback!! Message received Successfully!");
break;
}
else if (dis.readUTF().equals("failure"))
{
System.out.println("Message was not received successfully!");
break;
}
}
// Closing all connections
dis.close();
dos.close();
socket.close();
}
// Driver Method
public static void main(String args[]) throws IOException
{
Checksum_Sender cs = new Checksum_Sender(4444);
}
}
Check_Sum_Receiver.java
// Java code for Checksum_Receiver
package checksum_sender;
import java.net.*;
import java.io.*;
import java.util.*;
public class Checksum_Receiver {
// Initialize socket and I/O streams
private Socket s = null;
private DataInputStream dis = null;
private DataOutputStream dos = null;
// Constructor to put ip address and port
public Checksum_Receiver(InetAddress ip,int port)throws IOException
{
// Opens a socket for connection
s = new Socket(ip,port);
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
while (true)
{ Scanner sc = new Scanner(System.in);
int i, l, nob, sum = 0, chk_sum;
// Reads the data length sent by sender
l = dis.readInt();
// Initializes the arrays based on data length received
int c_data[] = new int[l];
int data[] = new int[l];
System.out.println("Data received (alond with checksum) is");
for(i = 0; i< data.length; i++)
{
// Reading the data being sent one by one
data[i] = dis.readInt();
System.out.println(data[i]);
// Complementing the data being received
nob = (int)(Math.floor(Math.log(data[i]) / Math.log(2))) + 1;
c_data[i] = ((1 << nob) - 1) ^ data[i];
// Adding the complemented data
sum += c_data[i];
}
System.out.println("Sum(in ones complement) is : "+sum);
// Complementing the sum
nob = (int)(Math.floor(Math.log(sum) / Math.log(2))) + 1;
sum = ((1 << nob) - 1) ^ sum;
System.out.println("Calculated Checksum is : "+sum);
// Checking whether final result is 0 or something else
// and sending feedback accordingly
if(sum == 0)
{
dos.writeUTF("success");
break;
}
else
{
dos.writeUTF("failure");
break;
}
}
// Closing all connections
dis.close();
dos.close();
s.close();
}
// Driver Method
public static void main(String args[])throws IOException
{
// Getting ip address on which the receiver is running
// Here, it is "localhost"
InetAddress ip = InetAddress.getLocalHost();
Checksum_Receiver cr = new Checksum_Receiver(ip,4444);
}
}
For anyone who reads this and finds this answer helpful to them. These were the fixes for my problems:
1: Make sure the port numbers match on both sender and receiver program. (sender:port=receiver:port)
2: Use your local IP address for the sender (127.0.0.1:port) and use (localhost:port) for the receiver! OR vice versa.
3: Then for data input start the sender program first but don't input anything yet, then start the receiver so the data-stream can be connected. Then input data as you like!

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.

Client-Server UDP connection

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?

Categories

Resources