I am having trouble sending data between a UDP Server and Client, I am trying to ,send an array of strings to the client from the server. The loop that I am using will hang up and stop reading the data from the server. If i pick a small number for the loop everything is okay it works but if I try to transmit the whole string it will stop half way and the client freezes up. Here is the server it reads a file and then sends the data to the client using a loop.
```
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class UDPServer1
{
public static void main(String[] args) throws Exception
{
int portNumber=9999;
UDPConnection com1 = null;
InetAddress ipAddress = InetAddress.getLocalHost();
Message MS1 = new Message();
char x = 0;
int m = 12, c=0;
double q;
int percent=20;
String[] message = new String[255];
String m1;
x = (char)m;
m1 = x + ""; //turn next page character into string
double rand = Math.random();
//String ACK="";
System.out.println("Enter the percentage of packet losses will happen in the transmission: ");
//percent = MS1.getInt();
DatagramSocket ds=new DatagramSocket(portNumber);
File infile = new File("COSC635_P2_DataSent.txt");
Scanner sc = new Scanner(infile);
// we just need to use next page as delimiter
sc.useDelimiter(m1);
while(sc.hasNext() ) //get data packets
{
message[c] = sc.next()+m1;
c++;
}
System.out.println("UDP server Started ");
byte[] data = new byte[6500];
DatagramPacket receivedFrame = new DatagramPacket(data, data.length);
ds.receive(receivedFrame);
String ACK = new String(receivedFrame.getData(),0, receivedFrame.getLength());
//str = message[80];
//receiveData(ds);
//com1.setPort(receivedFrame.getPort());
portNumber = receivedFrame.getPort();
byte[] frame;
//dp1;
//System.out.println("Dp port is " + dp.getPort());
int i = 0;
while( i<=c-1) //error control goes here
{
//frame = (message[i].trim() ).getBytes();
//ipAddress = InetAddress.getLocalHost();
//DatagramPacket sendFrame= new DatagramPacket(frame, frame.length, ipAddress, receivedFrame.getPort());
sendData(ds, message[i].trim()+ACK+ " port number is " + portNumber, InetAddress.getLocalHost(), portNumber);
//ds.receive(receivedFrame);
//ACK = receiveData(ds);
//simulate lost packets
//rand = Math.random();
//q = rand*100;
//if(percent < (int)q)
//ds.send(sendFrame);
i++;
}
//frame = ("End of File").getBytes();
//ipAddress = InetAddress.getLocalHost();
//sendFrame= new DatagramPacket(frame, frame.length, ipAddress, receivedFrame.getPort());
//ds.send(sendFrame);
ds.close();
}
static String receiveData(DatagramSocket socket) throws IOException
{
byte buffer[];
buffer = new byte[6500];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String received = new String(packet.getData(), 1, packet.getLength() - 1).trim();
System.out.println(received);
return received;
}
static void sendData(DatagramSocket ds, String data, InetAddress ipAddress, int portNumber) throws IOException
{
byte[] frame = null;
frame = (data.trim() ).getBytes();
DatagramPacket dp1= new DatagramPacket(frame, frame.length, ipAddress, portNumber);
//simulate lost packets
//rand = Math.random();
//q = rand*100;
//if(percent < (int)q)
ds.send(dp1);
}
}
```
Here is the code for the client.
```
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.lang.Math;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class UDPClient
{
public static void main(String[] args) throws Exception
{
DatagramSocket dsocket = new DatagramSocket();
String fileContent ="";
InetAddress ipAddress = InetAddress.getLocalHost();
int socketNumber=9999;
byte[] ACK = null;
FileWriter fileWriter = new FileWriter("COSC635_P2_DataRecieved.txt");
System.out.println("UDP Client Started");
String mess = "";
Message m1;
//send frames
//Frame is the string
ACK = (" ").getBytes();
DatagramPacket dp= new DatagramPacket(ACK, ACK.length, ipAddress, socketNumber);
dsocket.send(dp);
byte[] data = new byte[6500];
String str = "";
DatagramPacket dp1 = new DatagramPacket(data, data.length);
dsocket.receive(dp1);
str = new String(dp1.getData());
int i =0;
while( i<70) //error control needs to go here
{
//ds.receive(dp1);
//str = new String(dp1.getData(), 1, dp1.getLength() - 1).trim();
mess = receiveData(dsocket);
//mess = mess + " i is " + i;
System.out.println( mess.trim());
System.out.println( "inside loop");
//fileContent = fileContent + mess;
i++;
sendData(dsocket, "Packet Received " + i + " ", ipAddress, i);
}
//
//System.out.println(fileContent);
System.out.println("outside loop");
fileWriter.write(fileContent);
fileWriter.close();
dsocket.close();
System.out.println("data socket closed");
}
static String receiveData(DatagramSocket socket) throws IOException
{
byte buffer[];
buffer = new byte[6500];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String received = new String(packet.getData(), 1, packet.getLength() - 1).trim();
System.out.println(received);
return received;
}
static void sendData(DatagramSocket ds, String data, InetAddress ipAddress, int portNumber) throws IOException
{
byte[] frame = null;
frame = (data.trim() ).getBytes();
DatagramPacket dp1= new DatagramPacket(frame, frame.length, ipAddress, portNumber);
ds.send(dp1);
}
}
```
Related
I am trying to login Ericsson MD110 alex through the c# application. The md110 returned values that asking the username for login the application, but once I pass the username and password through the following code:
public static void Main(string[] args)
{
try
{
byte[] data = new byte[1024];
string stringData;
//TcpClient tcpclnt = new TcpClient();
//Console.WriteLine("Connecting.....");
string ipaddress = "192.168.1.30";
int port=23;
IPAddress ipadd = IPAddress.Parse(ipaddress);
IPEndPoint ipend = new IPEndPoint(ipadd, port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.NoDelay = false;
sock.Connect(ipend);
//recive data
int recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
//textBox4.AppendText(stringData + "\r\n");
Console.Write(stringData);
//while (true)
//{
Byte[] bBuf;
string buf;
//Application.DoEvents();
//buf = String.Format("{0}\r\n{1}\r\n", "MDUSER", "HELP");
buf = String.Format("ALREI;");
//buf = string.Format("ENTER USER NAME<.MDUSER;MDUSER;ENTER PASSWORD<.HELP;");
bBuf = Encoding.ASCII.GetBytes(buf);
sock.Send(bBuf);
data = new byte[1024];
recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
//textBox4.AppendText(stringData + "\r\n");
string df = "";
Console.Write(stringData);
Console.ReadLine();
//}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadKey();
}
}
Further, I checked with wireshark, but md110 doesn't return any value.
only acknowledge data packet will receive.
I need some advice.
Hi there I am new to java and network programming... I am trying to send two UDP packets from (AssignmentChatClient) to a server (AssignmentChatServer), the server will check the first packet which contains (IP address of destination) and then forward the second packet (message) to the destination (AssignmentChatClient2). I have a problem that the destination (AssignmentChatClient2) does not receive the packet... Could you guys help me to point out where the problem is ? Thanks in advance...
Here is the code
AssignmentChatServer
import java.net.*;
import java.io.*;
public class AssignmentChatServer {
public static void main(String args[]) throws IOException {
int sPort = 2222, cPort = 3333;
byte[] buf = null;
byte[] buf2 = null;
System.out.println("Listening to socket port " + sPort);
try (DatagramSocket serverSocket = new DatagramSocket(sPort)) {
while (true) {
buf = new byte[128];
buf2 = new byte [1024];
String addr = "";
String sMsg = "";
char [] tempC = null;
DatagramPacket addrPacket = null;
DatagramPacket msgPacket = null;
addrPacket = new DatagramPacket(buf, buf.length);
serverSocket.receive(addrPacket);
String address = new String(addrPacket.getData()).trim();
System.out.println(address);
tempC = address.toCharArray();
for(int i = 0; i < tempC.length; i++){
if(tempC[i] == '-'){
InetAddress sAddr = InetAddress.getByName(addr);
msgPacket = new DatagramPacket(buf2, buf2.length);
serverSocket.receive(msgPacket);
String msg = new String(msgPacket.getData());
sMsg = msg.trim();
msgPacket = new DatagramPacket(sMsg.getBytes(),sMsg.getBytes().length, sAddr, cPort);
serverSocket.send(msgPacket);
System.out.println(sMsg);
addr = "";
continue;
}
addr += tempC[i];
}
}
}catch(IOException ex){System.out.println(ex);}
}
}
AssignmentChatClient
import java.net.*;
import java.io.*;
public class AssignmentChatClient {
public static void main(String args[]) throws IOException {
int sPort = 2222, cPort = 3333;
byte[] buf = null;
byte[] buf2 = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter server address : ");
String serAddress = input.readLine();
InetAddress sAddr = InetAddress.getByName(serAddress);
System.out.println("Connecting to server socket on port " + sPort);
try (DatagramSocket clientSocket = new DatagramSocket(cPort)) {
while (true) {
buf = new byte[128];
buf2 = new byte [1024];
String temp = "";
String sMsg = "";
String rMsg = "";
DatagramPacket addrPacket = null;
DatagramPacket rlyPacket = null;
DatagramPacket msgPacket = null;
System.out.print("How many the number of users do you want to send to : ");
int nUsers = Integer.parseInt(input.readLine());
byte [] address = new byte [nUsers];
address = null;
System.out.print("Enter message : ");
sMsg = input.readLine();
if(sMsg == null)
return ;
for(int i = 0, j = 0; i < nUsers ; i++){
System.out.print("Please enter address " + ++j + " : ");
temp += input.readLine();
temp += "-";
}
address = temp.getBytes();
addrPacket = new DatagramPacket(address,address.length, sAddr, sPort);
clientSocket.send(addrPacket);
// System.out.println(temp);
msgPacket = new DatagramPacket(sMsg.getBytes(),sMsg.getBytes().length, sAddr, sPort);
clientSocket.send(msgPacket);
// System.out.println(sMsg);
// System.out.println(sAddr.toString());
rlyPacket = new DatagramPacket(buf2, buf2.length);
clientSocket.receive(rlyPacket);
String msg = new String(rlyPacket.getData());
rMsg = msg.trim();
System.out.println(rMsg);
}
}catch(IOException ex){System.out.println(ex);}
}
}
AssignmentChatClient2
import java.net.*;
import java.io.*;
public class AssignmentChatClient2 {
public static void main(String args[]) throws IOException {
int sPort = 2222, cPort = 3333;
byte[] buf = null;
byte[] buf2 = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter server address : ");
String serAddress = input.readLine();
InetAddress sAddr = InetAddress.getByName(serAddress);
System.out.println("Connecting to server socket on port " + sPort);
try (DatagramSocket clientSocket = new DatagramSocket(cPort)) {
while (true) {
buf2 = new byte [1024];
String temp = "";
String replyMsg = "";
String rMsg = "";
DatagramPacket addrPacket = null;
DatagramPacket rcvPacket = null;
DatagramPacket msgPacket = null;
rcvPacket = new DatagramPacket(buf2, buf2.length);
clientSocket.receive(rcvPacket);
String msg = new String(rcvPacket.getData());
rMsg = msg.trim();
System.out.println(rMsg);
InetAddress rAddr = rcvPacket.getAddress();
temp = rAddr.toString();
System.out.print("Enter message : ");
replyMsg = input.readLine();
if(replyMsg == null)
return ;
addrPacket = new DatagramPacket(temp.getBytes(),temp.getBytes().length, sAddr, sPort);
clientSocket.send(addrPacket);
// System.out.println(temp);
msgPacket = new DatagramPacket(replyMsg.getBytes(),replyMsg.getBytes().length, sAddr, sPort);
clientSocket.send(msgPacket);
// System.out.println(replyMsg);
// System.out.println(sAddr.toString());
}
}catch(IOException ex){System.out.println(ex);}
}
}
Remember that UDP is unreliable.
You should not rely on first packet arriving before (or ever) at the recipient.
You need to provide both the final destination address and the payload in one packet.
I am trying to set up a program that looks into UDP performance of packets and response times on my network. I have a client and server side class, for which I am specifying the packet size which to send pieces of text. For example, if I want to send a word of "Tester" in a 4 byte packet, it will send the "TEST" part but not reiterate through the rest of the word. I have tried to add in a while loop, but i don't think what I have is correct as it continuously sends the first 4 bytes. Does anyone know what sort of loop I need and where abouts it should be placed to get the outcome I am after? Code for the client is below. Many thanks in advance for any guidance.
//UDP Client
//Usage: java UDPClient [server addr] [server port]
import java.io.*;
import java.net.*;
public class UDPClient extends variable {
// static Integer portNo = 4444;
static Integer byteSize = 4;
public static void main(String[] args) throws Exception {
SocketForm form = new SocketForm();
long startTime; // Starting time of program, in milliseconds.
long endTime; // Time when computations are done, in milliseconds.
double time;
//get server address
String serverName = "localhost";
if (args.length >= 1)
serverName = args[0];
InetAddress serverIPAddress = InetAddress.getByName(serverName);
//get server port;
int serverPort = form.cliportNo;
if (args.length >= 2)
serverPort = Integer.parseInt(args[1]);
//create socket
DatagramSocket clientSocket = new DatagramSocket();
//get input from keybaord
byte[] sendData = new byte[byteSize];
BufferedReader inFromUser = new BufferedReader(new InputStreamReader (System.in));
while (true){ //incorrect as it is only repeating the first four bytes of the word typed in the console
String sentence = inFromUser.readLine();
startTime = System.currentTimeMillis();
sendData = sentence.getBytes();
//construct and send datagram;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, serverPort);
clientSocket.send(sendPacket);
//receive datagram
byte[] receiveData = new byte [byteSize];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
//print output
String sentenceFromServer = new String(receivePacket.getData());
System.out.println("From Server:" + sentenceFromServer);
//close client socket
//clientSocket.close();
endTime = System.currentTimeMillis();
time = endTime - startTime;
//System.out.println("Time :" + time);
}
} //end of main
} //end of UDPClient
Do you mean like this?
private void sendChunked( String msg, int chunkSizeInBytes ) {
byte[] msgBytes = msg.getBytes();
for( int index = 0; index < msgBytes.length ; index += chunkSizeInBytes ) {
DatagramPacket packet = new DatagramPacket( msgBytes, index, Math.min( chunkSizeInBytes, msgBytes.length-index ));
send( packet ); // You know how that works ...
}
}
I'm trying to send a DatagramPacket, and then must wait for an Acknowlegment from sever, so that I know if I have to resend the same packet or send the next one..
I'm using for that the same socket on the client, to send the datapacket and to receive the acknowlegment (ack), and same in the server's side, another socket that is used to receive the datapacket and then to send the acknowledgment to the client..
The 1st problem is that the client is sending the datapacket, the server is receiving it, then sends the acknowledgment to client, but the client blocks on receiving the Acknowledgment-packet.
I'm making some System.out.println to identify where is the problem, but I couldnt find any solution to this problem.
The 2nd problem is that the Server is still always receiving data, and dont wait for the client to send something, i checked that because i got that lines(like "got packet with length xxx" "ack sent with ackNr yyy" ..." printed on the server's side, all the time although the client is blocking after sending the 1st packet, because it's waiting for the acknowledgment that is not received!
Here is the CLIENT's code:
package blatt7;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.zip.CRC32;
public class FileSender {
String zielRechner;
String filePath;
InetAddress host;
File file;
FileInputStream fis;
int readLength;
int sequenceNr = 0;
int receivedSeqNr = 1;
static int port = 7777;
int packetNr = 0;
byte[] packet = new byte[1216];
byte[] data = new byte[1200];
byte[] header = new byte[16];
byte[] readLengthByte = new byte[4];
byte[] sequenceNrByte = new byte[4];
byte[] checksumByte = new byte[8];
byte[] ackBuffer = new byte[4];
CRC32 checksumCalculator = new CRC32();
DatagramPacket dp;
DatagramPacket ackPacket;
DatagramSocket sendSocket = null;
//DatagramSocket ackSocket = null;
static boolean ackReceived = true;
public FileSender(String zielRechner, String filePath) throws UnknownHostException, FileNotFoundException {
this.zielRechner = zielRechner;
this.filePath = filePath;
this.host = InetAddress.getByName(zielRechner);
this.file = new File(filePath);
fis = new FileInputStream(file);
}
public void sendFile() throws IOException {
while((readLength = fis.read(data)) != -1) {
if (sequenceNr == 1)
sequenceNr = 0;
else
sequenceNr = 1;
readLengthByte = intToBytes(readLength);
sequenceNrByte = intToBytes(sequenceNr);
for(int i=0; i<4; i++) {
header[8+i] = readLengthByte[i];
}
for(int i=0; i<4; i++) {
header[12+i] =sequenceNrByte[i];
}
int j=0;
for (int i=0; i<packet.length; i++) {
if (i < header.length)
packet[i] = header[i];
else {
packet[i] = data[j];
j++;
}
}
checksumCalculator.reset();
checksumCalculator.update(packet,8,8+readLength);
checksumByte = longToBytes(checksumCalculator.getValue());
for(int i=0; i < 8; i++) {
packet[i] = checksumByte[i];
}
dp = new DatagramPacket(packet, packet.length, host, port);
while(receivedSeqNr == sequenceNr && ackReceived) {
try {
ackReceived = false;
sendSocket = new DatagramSocket();
sendSocket.send(dp);
sendSocket.setSoTimeout(10000);
packetNr++;
System.out.println("Packet sent with seqNr: " + sequenceNr + " and length: " + bytesToInt(readLengthByte, 0) + " - PACKET NR: " + packetNr);
ackPacket = new DatagramPacket(ackBuffer, ackBuffer.length);
System.out.println("TEST!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
sendSocket.receive(ackPacket);
System.out.println("Receiving ACK!!");
ackReceived = true;
ackBuffer = ackPacket.getData();
receivedSeqNr = bytesToInt(ackBuffer,0);
System.out.println("got SequenceNr with receivedSeq-Nr: " + receivedSeqNr);
} catch (SocketTimeoutException e) {
e.printStackTrace();
break;
}
}
}
fis.close();
System.out.println("Transfer Completed Successfully!");
sendSocket.close();
}
public static byte[] longToBytes(long value) {
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putLong(value);
return buffer.array();
}
public static long bytesToLong(byte[] bytes, int index) {
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.put(bytes);
buffer.flip();//need flip
return buffer.getLong(index);
}
public static byte[] intToBytes(int value) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(value);
return buffer.array();
}
public static int bytesToInt(byte[] bytes, int index) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.put(bytes);
buffer.flip();//need flip
return buffer.getInt(index);
}
public static void main(String[] args) throws IOException,ClassNotFoundException {
FileSender sender = new FileSender("localhost", "C:/Users/Kb/Desktop/Deepophile - Psychedelic Sessions.wav");
sender.sendFile();
}
}
and here is the SERVER's code:
package blatt7;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.zip.CRC32;
public class FileReceiver {
byte[] incomingBuffer;
DatagramPacket incomingPacket;
DatagramSocket receiveSocket;
DatagramPacket ackPacket;
int packetCounter = 0;
int dataLength;
int receivedSeqNr;
long calculatedChecksum;
long receivedChecksum;
CRC32 checksumCalculator = new CRC32();
byte[] dataLengthByte = new byte[4];
byte[] receivedSeqNrByte = new byte[4];
byte[] receivedChecksumByte = new byte[8];
byte[] ackArray;
public FileReceiver() throws SocketException {
incomingBuffer = new byte[1500];
incomingPacket = new DatagramPacket(incomingBuffer, incomingBuffer.length);
}
public void receive() throws IOException {
receiveSocket = new DatagramSocket(FileSender.port);
receiveSocket.setSoTimeout(10000);
System.out.println("Server socket created. Waiting for incoming data...");
while(true && FileSender.ackReceived)
{
receiveSocket.receive(incomingPacket);
packetCounter++;
for (int i=0; i <4; i++) {
dataLengthByte[i] = incomingBuffer[8+i];
}
dataLength = FileSender.bytesToInt(dataLengthByte,0);
checksumCalculator.reset();
checksumCalculator.update(incomingBuffer, 8, dataLength+8);
calculatedChecksum = checksumCalculator.getValue();
for (int i=0; i <4; i++) {
receivedSeqNrByte[i] = incomingBuffer[12+i];
}
receivedSeqNr = FileSender.bytesToInt(receivedSeqNrByte,0);
for (int i=0; i <8; i++) {
receivedChecksumByte[i] = incomingBuffer[i];
}
long receivedChecksum = FileSender.bytesToLong(receivedChecksumByte,0);
System.out.println("Got packet with checksum: " + receivedChecksum);
System.out.println("Server-calculated checksum: " + calculatedChecksum);
System.out.println("Got packet with seqNr: " + receivedSeqNr + " and length: " + dataLength);
if (calculatedChecksum != receivedChecksum) {
sendACK(receivedSeqNr);
System.out.println("Packet have erros(s)! It must be sent another time!");
}
else if(calculatedChecksum == receivedChecksum && receivedSeqNr == 1) {
sendACK(0);
System.out.println("SeqNr '0' sent");
}
else if (calculatedChecksum == receivedChecksum && receivedSeqNr == 0) {
sendACK(1);
System.out.println("SeqNr '1' sent");
}
}
}
public void sendACK(int seqNum) throws IOException {
byte[] ackArray = FileSender.intToBytes(seqNum);
ackPacket = new DatagramPacket(ackArray, ackArray.length, InetAddress.getByName("localhost"), FileSender.port);
receiveSocket.send(ackPacket);
}
public static void main(String[] args) throws IOException,ClassNotFoundException {
FileReceiver receiver = new FileReceiver();
receiver.receive();
}
}
You can try to execute it to see where the problem is...
So PLEASE if you have ANY idea how can I solve this problem, let me know!
Thankyou verymuch!
Can anyone tell me where to find the received file? or how should I change my code so that I choose where to save it??
Yes it is possible. Your problem is that you have the target address:port wrong when sending the ACK datagram. You should get the target address:port from the received DatagramPacket, or simpler still just reuse that datagram with different data as the ACK datagram.
How server can send to client using own port? You are sending ACK from server to client on Server's port, you should get client's UDP port from received packet and send data to that port.
EDIT
Change in Server in SendACK method to:
ackPacket = new DatagramPacket(ackArray, ackArray.length, InetAddress.getByName("localhost"), incomingPacket.getPort());
And now analyze code by running.
My project consists of an application using which users can send files among themselves.
Hence as a basic unit, I developed a FileServer and a FileClient Program.
This code works perfectly fine on localhost but fails on the Network (wifi).
An estimated problem is that the client socket is getting closed or isn't responding after a certain point of time while recieving. But i cant really figure out what the problem is or how to approach the problem.
The error appears is a SocketException: Software caused connection abort. Socket write error.
FileServer CODE:
import java.net.*;
import java.io.*;
public class FileServerPC {
static String remoteIPaddress = "192.168.43.95";
static String filename;
String path;
static File selectedfile = null;
static ServerSocket servsock = null;
static Socket sock = null;
static FileInputStream fis;
static BufferedInputStream bis;
static DatagramSocket theSocket = null;
static DatagramPacket theOutput;
static OutputStream os;
byte[] mybytearray;
static double nosofpackets;
static int packetsize = 1024;
public FileServerPC() {
try {
servsock = new ServerSocket(1500);
theSocket = new DatagramSocket(9999);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
FileServerPC fs = new FileServerPC();
selectedfile = new File("C:\\flower.jpg");
filename = selectedfile.getName();
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
System.out.println("Waiting...");
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
fis = new FileInputStream(selectedfile);
System.out.println((int) selectedfile.length());
long length = selectedfile.length();
System.out.println("LENGTH: " + length);
nosofpackets = Math
.ceil(((int) selectedfile.length()) / packetsize);
// progressBar.setValue(50);
bis = new BufferedInputStream(fis);
String message = length + "`~`" + filename;
byte[] data = message.getBytes();
theOutput = new DatagramPacket(data, data.length,
InetAddress.getByName(remoteIPaddress),8888);
theSocket.send(theOutput);
byte[] newbytearray = new byte[packetsize];
int dur = (int) (selectedfile.length());
int dur1 = dur / 100;
int counter = 0;
System.out.println("duration: " + dur + "nosofpackets: "
+ nosofpackets + "dur1: " + dur1);
int val = 0;
for (int i = 0; i <= nosofpackets ; i++) {
os = sock.getOutputStream();
bis.read(newbytearray, 0, newbytearray.length);
os.write(newbytearray, 0, newbytearray.length);
counter = counter + newbytearray.length;
val = counter / dur1;
System.out.println(val);
os.flush();
}
System.out.println(val);
os.flush();
os.close();
sock.close();
theSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
}
FileClient CODE:
import java.net.*;
import java.io.*;
public class FileClientPC
{
public static void main(String[] args) throws IOException
{
long start = System.currentTimeMillis();
String remoteip="192.168.43.237";
Socket sock = new Socket(remoteip, 1500);
System.out.println("Connecting...");
InputStream is = sock.getInputStream();
DatagramSocket ds = new DatagramSocket(8888);
byte[] buffer = new byte[65507];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
try {
ds.receive(dp);
} catch (IOException e) {
System.err.println("chat error2 " + e);
}
String s = new String(dp.getData(), 0, dp.getLength());
String temp[]=s.split("`~`");
String size = temp[0];
String name = temp[1];
System.out.println(size +" "+ name);
long sizeint = Integer.parseInt(size);
System.out.println("Filename: " + name);
FileOutputStream fos = new FileOutputStream("D:\\"+name);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int packetsize = 1024;
double nosofpackets = Math.ceil(sizeint / packetsize);
System.out.println("No of packets: "+Double.toString(nosofpackets));
byte newbytearray[];
for (int i = 0; i <= nosofpackets; i++) {
is = sock.getInputStream();
newbytearray = new byte[packetsize];
int bytesRead = is.read(newbytearray, 0, newbytearray.length);
System.out.println("Packet:" + (i + 1));
bos.write(newbytearray, 0, newbytearray.length);
}
long end = System.currentTimeMillis();
bos.close();
sock.close();
ds.close();
}
}
You need to specify which interface you want to listen to. The default is the local interface. (probably OS dependent). The API for ServerSocket explains how this works (the constructor and bind() functions for instance).