Make UDPServer send to UDPClient - java

I'm trying to send data to the client but I have not figured out
This is my code.
UDP-Client:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket datagramSocket = new DatagramSocket( );
InetAddress ipServer = InetAddress.getByName("localhost");
byte[] sendDatagram = new byte[1054];
byte[] sendDatagramB = new byte[1055];
byte[] sendDatagramC = new byte[1056];
byte[] receiveDatagram = new byte[1054];
byte[] receiveDatagramB = new byte[1055];
byte[] receiveDatagramC = new byte[1056];
while (true) {
System.out.println("Ingrese X");
String msgA = input.readLine();
System.out.println("Ingrese B");
String msgB = input.readLine();
System.out.println("Ingrese C");
String msgC = input.readLine();
sendDatagram = (msgA.getBytes());
DatagramPacket sendPacket = new DatagramPacket(sendDatagram, sendDatagram.length, ipServer, 6667);
datagramSocket.send(sendPacket);
sendDatagramB = (msgB.getBytes());
DatagramPacket sendPacketB = new DatagramPacket(sendDatagramB, sendDatagramB.length, ipServer, 6667);
datagramSocket.send(sendPacketB);
sendDatagramC = (msgC.getBytes());
DatagramPacket sendPacketC = new DatagramPacket(sendDatagramC, sendDatagramC.length, ipServer, 6667);
datagramSocket.send(sendPacketC);
}
UDP-Server:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket datagramSockets = new DatagramSocket( );
InetAddress ipServer = InetAddress.getByName("localhost");
byte[] sendDatagrams = new byte[1054];
byte[] receiveDatagrams = new byte[1054];
DatagramSocket datagramSocket = new DatagramSocket(6667);
byte[] sendDatagram = new byte[1054];
byte[] receiveDatagram = new byte[1054];
byte[] sendDatagramB = new byte[1055];
byte[] receiveDatagramB = new byte[1055];
byte[] sendDatagramC = new byte[1056];
byte[] receiveDatagramC = new byte[1056];
System.out.println("Server Start");
while (true){
DatagramPacket receivePacket = new DatagramPacket(receiveDatagram,receiveDatagram.length);
datagramSocket.receive(receivePacket);
String receive = new String(receivePacket.getData());
System.out.println(receive+"x");
InetAddress ipClient = receivePacket.getAddress();
int portClient = receivePacket.getPort();
receiveDatagram = new byte[1054];
String msgClient = "Hola Mundo";
DatagramPacket receivePacketB = new DatagramPacket(receiveDatagramB,receiveDatagramB.length);
datagramSocket.receive(receivePacketB);
String receiveB = new String(receivePacketB.getData());
System.out.println(receiveB+"y");
InetAddress ipClientB = receivePacketB.getAddress();
int portClientB = receivePacketB.getPort();
receiveDatagramB = new byte[1055];
String msgClientB = "Hola Mundo";
DatagramPacket receivePacketC = new DatagramPacket(receiveDatagramC,receiveDatagramB.length);
datagramSocket.receive(receivePacketC);
String receiveC = new String(receivePacketC.getData());
System.out.println(receiveC+"z");
InetAddress ipClientC = receivePacketC.getAddress();
int portClientC = receivePacketC.getPort();
receiveDatagramC = new byte[1056];
String msgClientC = "Hola Mundo";
Double x1 = (-portClientB - (Math.sqrt((portClient*portClientB - ((4*portClient*portClientC))))))/ (2 * portClientC);
Double x2 = (-portClientB + (Math.sqrt((portClient*portClientB - ((4*portClient*portClientC))))))/ (2 * portClientC);
String xa = String.valueOf(x1);
String xb = String.valueOf(x2);
System.out.println("El Resultado de x1 es = "+" "+x1);
System.out.println("El Resultado de x1 es = "+" "+x2);
}
I suppose to send String XA and XB to the client.

I don't know what you are really doing with udp socket but generally a server must support all the requests including a protocol from clients.
This is what my udp socket server looks like from your source as follows:
package justtest;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(6667);
byte[] sendDatagram = new byte[1054];
byte[] receiveDatagram = new byte[1054];
System.out.println("Server Start");
try
{
while (true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveDatagram, receiveDatagram.length);
datagramSocket.receive(receivePacket);
//System.out.println("len" + receivePacket.getLength());
String receive = new String(receivePacket.getData());
System.out.println(receive.trim() + " received...");
//////// Do it what you want here //////////
//////// done //////////////////////////////
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String msgClient = "Hola Mundo";
System.arraycopy(msgClient.getBytes(), 0, sendDatagram, 0, msgClient.getBytes().length);
DatagramPacket sendPacket = new DatagramPacket(sendDatagram, sendDatagram.length, IPAddress, port);
datagramSocket.send(sendPacket);
}
}
finally
{
datagramSocket.close();
}
}
}
Then, the udp client can do what you are supposed to do.
package justtest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClient {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
InetAddress ipServer = InetAddress.getByName("localhost");
DatagramSocket datagramSocket = null;
DatagramSocket datagramSocketA = null;
DatagramSocket datagramSocketB = null;
byte[] sendDatagram = new byte[1054];
byte[] sendDatagramB = new byte[1055];
byte[] sendDatagramC = new byte[1056];
byte[] receiveDatagram = new byte[1054];
byte[] receiveDatagramB = new byte[1055];
byte[] receiveDatagramC = new byte[1056];
while (true)
{
System.out.println();
System.out.println("Ingrese X");
String msgA = input.readLine();
//sendDatagram = (msgA.getBytes());
System.arraycopy(msgA.getBytes(), 0, sendDatagram, 0, msgA.getBytes().length);
DatagramPacket sendPacket = new DatagramPacket(sendDatagram, sendDatagram.length, ipServer, 6667);
DatagramPacket recvPacket = new DatagramPacket(sendDatagram, receiveDatagram.length, ipServer, 6667);
datagramSocket = new DatagramSocket();
datagramSocket.send(sendPacket);
datagramSocket.receive(recvPacket);
System.out.printf("Send...[%s]/ recv...[%s]", new String(sendDatagram).trim(), new String(recvPacket.getData()).trim());
System.out.println();
System.out.println("Ingrese B");
String msgB = input.readLine();
//sendDatagramB = (msgB.getBytes());
System.arraycopy(msgB.getBytes(), 0, sendDatagramB, 0, msgB.getBytes().length);
DatagramPacket sendPacketB = new DatagramPacket(sendDatagramB, sendDatagramB.length, ipServer, 6667);
DatagramPacket recvPacketB = new DatagramPacket(receiveDatagramB, receiveDatagramB.length, ipServer, 6667);
datagramSocketA = new DatagramSocket();
datagramSocketA.send(sendPacketB);
datagramSocketA.receive(recvPacketB);
System.out.printf("Send...[%s]/ recv...[%s]", new String(sendDatagramB).trim(), new String(recvPacketB.getData()).trim());
System.out.println();
System.out.println("Ingrese C");
String msgC = input.readLine();
//sendDatagramC = (msgC.getBytes());
System.arraycopy(msgC.getBytes(), 0, sendDatagramC, 0, msgC.getBytes().length);
DatagramPacket sendPacketC = new DatagramPacket(sendDatagramC, sendDatagramC.length, ipServer, 6667);
DatagramPacket recvPacketC = new DatagramPacket(receiveDatagramC, receiveDatagramC.length, ipServer, 6667);
datagramSocketB = new DatagramSocket();
datagramSocketB.send(sendPacketC);
datagramSocketB.receive(recvPacketC);
System.out.printf("Send...[%s]/ recv...[%s]", new String(sendDatagramC).trim(), new String(recvPacketC.getData()).trim());
datagramSocket.close();
datagramSocketA.close();
datagramSocketB.close();
}
}
}
I think it is important what you will exactly do with the code.
Good luck.

Related

I'm having trouble creating a simple Java UDP system

The sequence numbers aren't working as the int value seems to reset to 0 - or setting it again in the second method returns an error.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Client3.sendThenReceive(Client3.java:106)
at Client3.stopAndWait(Client3.java:69)
at Client3.main(Client3.java:41)
This is the client:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.nio.*;
public class Client3 {
private DatagramSocket datagramSocket;
private InetAddress inetAddress;
private byte [] buffer;
private int initialSequenceNumber = 100;
private int sequenceNumber;
private int testSN;
private static final int port = 1234;
private static final int BUFFER_SIZE = 1024;
private static final String HOSTNAME = "localhost";
private static String message;
public Client3(DatagramSocket datagramSocket, InetAddress inetAddress) {
this.datagramSocket = datagramSocket;
this.inetAddress = inetAddress;
}
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress inetAddress = InetAddress.getByName(HOSTNAME);
Client3 client = new Client3(datagramSocket, inetAddress);
System.out.println("Send datagram packets to a server");
Scanner scanner = new Scanner(System.in);
message = (scanner.nextLine() + " Umbrella");
scanner.close();
client.stopAndWait();
}
public void stopAndWait() throws IOException {
Client3 client = new Client3(datagramSocket, inetAddress);
sequenceNumber = initialSequenceNumber;
ByteArrayOutputStream test = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(test);
toSend.writeInt(sequenceNumber);
buffer = test.toByteArray();
DatagramPacket testConnection = new DatagramPacket(buffer, buffer.length, inetAddress, port);
System.out.println("testConnection sent, waiting for confirmation.");
datagramSocket.send(testConnection);
datagramSocket.receive(testConnection);
ByteArrayInputStream confirmConnection = new ByteArrayInputStream(testConnection.getData());
DataInputStream dis = new DataInputStream(confirmConnection);
int SN = dis.readInt();
//test code to show the received data to the console
//System.out.println(SN);
if (SN == sequenceNumber) {
System.out.println("Confirmation received. Proceeding to Message delivery.");
//testSN = sequenceNumber;
//System.out.println("test: " + testSN + " SN: " + sequenceNumber);
client.sendThenReceive();
}
else {
System.out.println("error - incorrect sequence number.");
}
}
public void sendThenReceive() {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
// Changing the variable here results in error and termination
//Is it because it is in the method?
//int newNumber = 101;
//testSN = 101;
//sequenceNumber = 101;
ByteArrayOutputStream test = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(test);
System.out.println("test: " + testSN + " SN: " + sequenceNumber);
toSend.writeInt(sequenceNumber);
toSend.writeUTF(message);
buffer = test.toByteArray();
System.out.println(message + " " + sequenceNumber);
DatagramPacket sentMessage = new DatagramPacket(buffer, buffer.length, inetAddress, port);
datagramSocket.send(sentMessage);
datagramSocket.receive(sentMessage);
ByteArrayInputStream test2 = new ByteArrayInputStream(sentMessage.getData());
DataInputStream dis = new DataInputStream(test2);
int SN = dis.readInt();
String messageFromServer = dis.readUTF();
if (SN == 101) {
System.out.println("The server says you said: " + messageFromServer);
sequenceNumber++;
Scanner newScanner = new Scanner(System.in);
message = (newScanner.nextLine() + " Umbrella");
newScanner.close();
}
else {
System.out.println("Error - incorrect sequence number.");
}
} catch (IOException e) {
e.printStackTrace();
break;
}
} scanner.close();
}
}
And this is the server:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.io.*;
import java.net.*;
import java.nio.*;
public class Server3 {
private DatagramSocket datagramSocket;
private byte[] dataForSend = new byte[256];
byte[] receiveData = new byte[ dataForSend_SIZE ];
//byte[] dataForSend = new byte[ dataForSend_SIZE ];
private int initialSequenceNumber = 100;
private int sequenceNumber;
private static final int port = 1234;
private static final int dataForSend_SIZE = 1024;
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(port);
Server3 server = new Server3(datagramSocket);
System.out.println("Server Operational");
server.testConnection();
}
public Server3(DatagramSocket datagramSocket) {
this.datagramSocket = datagramSocket;
}
public void testConnection() throws IOException {
while (true) {
try {
sequenceNumber = initialSequenceNumber;
DatagramPacket receivedMessage = new DatagramPacket (receiveData, receiveData.length);
datagramSocket.receive(receivedMessage);
InetAddress inetAddress = receivedMessage.getAddress();
int port = receivedMessage.getPort();
ByteArrayInputStream test = new ByteArrayInputStream(receivedMessage.getData());
DataInputStream dis = new DataInputStream(test);
int a10 = dis.readInt();
System.out.println("SN read from Datagram: " + a10);
if ( a10 == sequenceNumber) {
System.out.println("Connection Test Successfully Received.");
ByteArrayOutputStream confirmConnection = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(confirmConnection);
toSend.writeInt(sequenceNumber);
dataForSend = confirmConnection.toByteArray();
DatagramPacket testConnection = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
datagramSocket.send(testConnection);
System.out.println("'confirmConnection' has been sent.");
sequenceNumber++;
receiveThenSend();
}
else {
System.out.println("error - incorrect sequence number."); }
}
finally {
}
}
}
public void receiveThenSend() throws IOException {
while (true) {
try {
sequenceNumber = 101;
DatagramPacket sentMessage = new DatagramPacket(receiveData, receiveData.length);
datagramSocket.receive(sentMessage);
InetAddress inetAddress = sentMessage.getAddress();
int port = sentMessage.getPort();
ByteArrayInputStream test = new ByteArrayInputStream(sentMessage.getData());
DataInputStream dis = new DataInputStream(test);
int SN = dis.readInt();
System.out.println("SN received: " + SN);
System.out.println("SN on File: " + sequenceNumber);
String messageFromClient = dis.readUTF();
if (SN == sequenceNumber) {
//String messageFromClient = new String(sentMessage.getData(), 0, sentMessage.getLength());
System.out.println("SN: Match.");
System.out.println("Message from Client: " + messageFromClient);
System.out.println("Response sent.");
ByteArrayOutputStream serverResponse = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(serverResponse);
toSend.writeInt(101);
toSend.writeUTF(messageFromClient);
dataForSend = serverResponse.toByteArray();
sentMessage = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
datagramSocket.send(sentMessage);
}
else {
System.out.println("Error - incorrect sequence number.");
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}
Can anyone see why these would be resetting, please?
The Exception you're getting is caused by closing the Scanner. When a Scanner instance is closed, it closes the underlying stream which is System.in in your case.
So next time when you create the Scanner, it's created over a closed stream and .nextLine() throws the exception you're seeing.
Here's a snippet that reproduces the issue:
Scanner s1 = new Scanner(System.in);
s1.close();
Scanner s2 = new Scanner(System.in);
s2.nextLine(); //Exception in thread "main" java.util.NoSuchElementException: No line found

Java UDP client not receiving from server(simple client server udp code)

I am a newbie in java networking , i made a client-server udp program. The server side is working fine but the client side is not receiving anything from server . Please correct the mistake.The server side is fully running but the client side is not working till its end . Any help would be great.
public class Client {
public static void main (String args[]) throws Exception {
DatagramSocket s = new DatagramSocket();
String msg = "Hello! ,from client. ";
byte[] b = msg.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(b, b.length, ia, 9999);
s.send(dp);
byte[] b2 = new byte[1024]; //byte array
DatagramPacket dip = new DatagramPacket(b2, b2.length);
s.receive(dip);
String str = new String(dip.getData());
System.out.println("From server" + str);
}
}
public class Server {
void run() throws Exception {
DatagramSocket ds = new DatagramSocket(9999);
byte [] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
String msg = new String(dp.getData());
System.out.println("Message from client:" + msg);
//giving back to client
String str = "HI!, from server.";
byte[] b2 = str.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dop = new DatagramPacket(b2, b2.length, ia, 9999);
ds.send(dop);
System.out.println("Message sent back");
ds.close();
}
public static void main(String args[]) throws Exception {
Server server = new Server();
server.run();
}
}
Your server is sending all responses to localhost, on port 9999. You need to update the server, so that it reads the address of the sender:
InetAddress ia = dp.getAddress();
int port = dp.getPort();
DatagramPacket dop = new DatagramPacket(b2, b2.length, ia, port);
The error is your server and client run on the same host, so they must listen on different ports like below:
The server
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Server {
void run() throws Exception {
DatagramSocket ds = new DatagramSocket(9999);
byte [] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
String msg = new String(dp.getData(),0,dp.getLength(),"UTF-8");
System.out.println("Message from client:" + msg);
//giving back to client
String str = "HI!, from server.";
byte[] b2 = str.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dop = new DatagramPacket(b2, b2.length, ia, 9998);
ds.send(dop);
System.out.println("Message sent back");
ds.close();
}
public static void main(String args[]) throws Exception {
Server server = new Server();
server.run();
}
}
and the client
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main (String args[]) throws Exception {
DatagramSocket s = new DatagramSocket(9998);
String msg = "Hello! ,from client. ";
byte[] b = msg.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(b, b.length, ia, 9999);
s.send(dp);
byte[] b2 = new byte[1024]; //byte array
DatagramPacket dip = new DatagramPacket(b2, b2.length);
s.receive(dip);
String str = new String(dip.getData(),0,dip.getLength(),"UTF-8");
System.out.println("From server" + str);
}
}

Why won't this work when sending an image file?

Server receives a file that the client sends.
When a text file is chosen, the transfer and the writing of the file is a success, but when an image file is chosen, either the transfer or the writing of the file generates some characters not found within the original file, thus corrupting the image file. Please help :)
public class Server {
private DatagramSocket socket = null;
private DatagramPacket inPacket;
private DatagramPacket outPacket = null;
private byte[] inBuffer, outBuffer;
private final int port = 50000;
private ChooseDestination cf = new ChooseDestination();
private BufferedWriter bw;
private int receivedNo = 1;
public static void main(String[] args) {
new Server();
}
public Server(){
this.connect();
}
public void connect(){
try{
socket = new DatagramSocket(port);
String fName = "";
while(true){
inPacket = null;
// waiting for input from client
inBuffer = new byte[1024];
inPacket = new DatagramPacket(inBuffer, inBuffer.length);
socket.receive(inPacket);
// get info of client
int source_port = inPacket.getPort();
InetAddress source_address = inPacket.getAddress();
System.out.println("Client: " + source_address + " Port:" + source_port);
// converts packets received to string for content checking
String data = new String(inPacket.getData(), 0, inPacket.getLength());
if(data.contains("filename")){
System.out.println("filename set");
fName = cf.browseFolders() + data.substring(8);
System.out.println("filename: " +fName);
outBuffer = new byte[1024];
outBuffer = ("ok").getBytes();
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, source_address, source_port);
socket.send(outPacket);
}
if (data.endsWith("ERROR!")) {
System.out.println("File doesn't exist.\n");
socket.close();
}
else if (!(data.contains("filename"))){
File file = new File(fName);
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileOutputStream fileOuputStream = new FileOutputStream(fName, true);
data = data.trim();
byte[] write = data.getBytes();
fileOuputStream.write(write);
fileOuputStream.close();
// sending acknowledgments formatted as ACKn where n is the packet received
outBuffer = new byte[1024];
outBuffer = ("ACK" + receivedNo + "").getBytes();
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, source_address, source_port);
socket.send(outPacket);
receivedNo++;
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
client sends the file to the server
public class Client {
private DatagramSocket socket = null;
private DatagramPacket inPacket;
private DatagramPacket outPacket = null;
private byte[] inBuffer, outBuffer;
private final int port = 50000;
private int packetNo = 1;
public Client(){
ChooseFile cf = new ChooseFile();
String fName = cf.BrowseFilesView();
this.sendFile(fName);
}
public static void main(String[] args) {
new Client();
}
public void sendFile(String fName){
try {
InetAddress address = InetAddress.getByName("192.168.1.15");
socket = new DatagramSocket();
Path path = Paths.get(fName);
byte[] data = Files.readAllBytes(path);
outBuffer = new byte[1024];
System.out.println(fName);
String[] tag = fName.split("\\\\");
System.out.println(tag[tag.length-1]);
outBuffer = ("filename"+tag[tag.length-1]).getBytes();
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, address, port);
socket.send(outPacket);
String s = null;
int i = 0;
int orig = 0;
while(i < data.length){
i = orig;
byte[] send = new byte[1024];
for( int ii = 0; ii < 1024 && i < data.length; ii++, i++){
send[ii] = data[i];
}
outBuffer = new byte[1024];
outBuffer = send;
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, address, port);
socket.send(outPacket);
inBuffer = new byte[1024];
inPacket = new DatagramPacket(inBuffer, inBuffer.length);
socket.receive(inPacket);
String ack = new String(inPacket.getData(), 0, inPacket.getLength());
int ackNo = 0;
try{
ackNo = Integer.parseInt(ack.substring(3));
}
catch(Exception e){
e.printStackTrace();
}
if (packetNo == ackNo){
System.out.println(packetNo + " " + ackNo);
orig = i;
packetNo++;
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java - creating threads for different tasks

public class server implements Runnable {
private static final int initialize_server_Port = 8080 ;
private static final int store_server_Port = 8181;
private static final int search_server_Port = 8282;
private static String tname ;
private static InetAddress address ;
protected static Hashtable<String , InetAddress> file_location = new Hashtable<String ,InetAddress>();
server(String tname){
this.tname = tname ;
}
public void run(){
try{
if("storeRecords".equals(tname))
storeRecord();}catch(IOException e ){
System.out.println("error: unable to create store socket");
}
try{
if("searchRecords".equals(tname))
searchRecord();}catch(IOException e){
System.out.println(e);
}
// if("search".equals(tname))
// searchRecord();
}
public void start(){
Thread thread = new Thread(this , tname );
thread.start();
}
public static void storeRecord() throws IOException{
System.out.println("store out");
DatagramSocket serverSocket = new DatagramSocket(store_server_Port);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true){
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String file = new String( receivePacket.getData());
file = file.trim();
System.out.println("RECEIVED: " + file);
InetAddress IPAddress = receivePacket.getAddress();
address = IPAddress;
int port = receivePacket.getPort();
System.out.println(file);
file_location.put(file , IPAddress);
String confirmation= "Successfully uploaded";
sendData = confirmation.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
public static void searchRecord() throws IOException{
System.out.println("search out");
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
DatagramSocket serverSocket = new DatagramSocket(search_server_Port);
while(true){
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String file = new String( receivePacket.getData());
file = file.trim();
System.out.println("RECEIVED: " + file);
InetAddress IPAddress = receivePacket.getAddress();
address = IPAddress;
int port = receivePacket.getPort();
boolean found = file_location.containsKey(file);
if(found == true ){
InetAddress query = file_location.get(file);
String confirmation= "found";
sendData = confirmation.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);}
else if (found != true){
String confirmation= "404";
sendData = confirmation.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
protected static String server_IP ;
public static void main(String[] args) throws IOException {
server storeThread = new server("storeRecords"); //**************
storeThread.start();
server searchThread = new server("searchRecords");
searchThread.start(); //*********************************
// PrintWriter pw = null ;
//Socket socket = null ;
try {
InetAddress iAddress = InetAddress.getLocalHost();
server_IP = iAddress.getHostAddress();
System.out.println("Server IP address : " +server_IP);
} catch (UnknownHostException e) {
}
DatagramSocket serverSocket = new DatagramSocket(initialize_server_Port);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String confirmation= "Successfully initialized";
sendData = confirmation.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
So right now the output is
search out
search out
what im trying to do is create three threads, one thread running the main, 2nd thread running storeRecord which should printout Store out
and 3rd running searchRecord ,
what am i doing wrong here?
In your code, tname is a static variable, hence, shared by all instances of server. It is assigned twice in two calls to the constructor. Making it an instance variable (i.e., removing the static) should do what you want.

Couldn't write in a file when receiving the data via socket connection in java

I tried to implement a send-receive example via a socket but It didn't work well. The sender sends the data successfully and the Receiver receives the data and shown in the console but I want to save this data in a file and I couldn't. As I noticed that the receiver keeps listeninig without ending the while loop. So can anyone help me to solve this problem ?
The Sender module
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPSend {
public static void main(String[] args) throws IOException
{
FileInputStream fstream = new FileInputStream("T.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
File file = new File("T.txt");
FileInputStream fis = new FileInputStream(file);
byte[] fsize = new byte[(int) file.length()];
int size = fis.read(fsize);
System.out.println("Size = " + size);
InetAddress addr = InetAddress.getByName("localhost");
byte[] buf = new byte[10000];
String DataLine;
while ((DataLine = br.readLine()) != null)
{
DatagramPacket packet =new DatagramPacket(DataLine.getBytes(), DataLine.length() , addr, 4555);
System.out.println (DataLine);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
}//end while loop
}//end main method
}
The Receiver module
import java.io.*;
import java.net.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class UDPRecieve {
public static void main(String args[]) throws Exception
{
FileWriter fw = new FileWriter(new File("D:/JavaPrograms/Multimedia-proj-2/src/outtt.txt"));
fw.write("hi");
try{
//DatagramSocket serverSocket = new DatagramSocket(4555);
DatagramSocket Socket = new DatagramSocket(4555);
byte[] receiveData = new byte[1000000];
// byte[] sendData = new byte[1024];
//while(true)
while(receiveData !=null)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
Socket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
fw.write(sentence);
fw.flush();
System.out.printf("RECEIVED: %s " , new String(receivePacket.getData()));
//System.out.println("Done");
//InetAddress IPAddress = receivePacket.getAddress();
//int port = receivePacket.getPort();
//String capitalizedSentence = sentence.toUpperCase();
/* sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);*/
}
fw.flush();
fw.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
Thanks in advance.
You can achive it by following code changes.In Receiver class make changes in following loop.
while (receiveData != null) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
Socket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
fw.write(sentence.trim());
fw.flush();
System.out.printf("RECEIVED: %s ", new String(receivePacket
.getData()));
// System.out.println("Done");
// InetAddress IPAddress = receivePacket.getAddress();
// int port = receivePacket.getPort();
// String capitalizedSentence = sentence.toUpperCase();
/*
* sendData = capitalizedSentence.getBytes(); DatagramPacket
* sendPacket = new DatagramPacket(sendData, sendData.length,
* IPAddress, port); serverSocket.send(sendPacket);
*/
}
EDIT
Complete Code of the Program which is running successfully.
Sender
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPSend {
public static void main(String[] args) throws IOException
{
FileInputStream fstream = new FileInputStream("D:/T.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
File file = new File("D:/T.txt");
FileInputStream fis = new FileInputStream(file);
byte[] fsize = new byte[(int) file.length()];
int size = fis.read(fsize);
System.out.println("Size = " + size);
InetAddress addr = InetAddress.getByName("localhost");
byte[] buf = new byte[10000];
String DataLine;
while ((DataLine = br.readLine()) != null)
{
DatagramPacket packet =new DatagramPacket(DataLine.getBytes(), DataLine.length() , addr, 4555);
System.out.println (DataLine);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
}//end while loop
}//end main method
}
Receiver
import java.io.File;
import java.io.FileWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPReceive {
public static void main(String args[]) throws Exception {
FileWriter fw = new FileWriter(new File(
"D:/outtt.txt"));
fw.write("hi");
try {
// DatagramSocket serverSocket = new DatagramSocket(4555);
DatagramSocket Socket = new DatagramSocket(4555);
byte[] receiveData = new byte[1000000];
// byte[] sendData = new byte[1024];
// while(true)
while (receiveData != null) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
Socket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
fw.write(sentence.trim());
fw.flush();
System.out.printf("RECEIVED: %s ", new String(receivePacket
.getData()));
// System.out.println("Done");
// InetAddress IPAddress = receivePacket.getAddress();
// int port = receivePacket.getPort();
// String capitalizedSentence = sentence.toUpperCase();
/*
* sendData = capitalizedSentence.getBytes(); DatagramPacket
* sendPacket = new DatagramPacket(sendData, sendData.length,
* IPAddress, port); serverSocket.send(sendPacket);
*/
}
fw.flush();
fw.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
Look at your receiver loop:
while(receiveData != null)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
Socket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
fw.write(sentence);
fw.flush();
System.out.printf("RECEIVED: %s " , new String(receivePacket.getData()));
}
Leaving aside the various character encoding issues etc, how would you ever expect receiveData to become null in that loop? How could the loop end?
Given that you're using UDP instead of TCP, you don't really have a connection, so how are you expecting to tell when the writer has stopped writing? Additionally, you should the consider the possibility of packets arriving out of order.

Categories

Resources