UDP Client/Server object transfer help - java

I'm trying to transfer an ArrayList from a client to a server using the UDP protocol.
The transfer starts at the "max" if statement.
Same in the server side
This is the client:
public class UdpClient {
protected DatagramPacket sendPacket;
protected DatagramPacket receivePacket;
public static void main(String args[]) throws IOException,
ClassNotFoundException {
UdpClient upd = new UdpClient();
ArrayList<Integer> arr = new ArrayList<Integer>();
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ObjectOutput oo = new ObjectOutputStream(bStream);
ByteArrayInputStream baos;
ObjectInputStream oos;
System.out
.println("Commands: Time, Date, Weather, Sum-number, Max-number, Exit");
while (true) {
String fromUsr = inFromUser.readLine();
if (fromUsr.equals("bye")) {
break;
} else if (fromUsr.equals("weather")) {
sendData = fromUsr.getBytes();
upd.sendPacket(sendData, clientSocket);
System.out
.println("Please select a ctiy: Lund, Malmo, Stockholm");
String weather = inFromUser.readLine();
sendData = weather.getBytes();
upd.sendPacket(sendData, clientSocket);
upd.receivePacket(clientSocket, receiveData);
} else if (fromUsr.equals("max")) {
sendData = fromUsr.getBytes();
upd.sendPacket(sendData, clientSocket);
String max = inFromUser.readLine().trim();
upd.nums(max, arr);
oo.writeObject(arr);
byte[] buf = new byte[bStream.toByteArray().length];
buf = bStream.toByteArray();
upd.sendPacket(buf, clientSocket);
System.out.println(arr);
} else {
// send data that of the user
sendData = fromUsr.getBytes();
upd.sendPacket(sendData, clientSocket);
upd.receivePacket(clientSocket, receiveData);
}
String fromServer = new String(upd.getData());
System.out.println("Message from server:\n" + fromServer);
}
}
private void sendPacket(byte[] sendData, DatagramSocket clientSocket)
throws IOException {
InetAddress IPAddress = InetAddress.getByName("ericman-PC");
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
9876);
clientSocket.send(sendPacket);
}
private void receivePacket(DatagramSocket serverSocket, byte[] receiveData)
throws IOException {
byte[] rData = new byte[1024];
receiveData = rData;
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
}
This is the Server
public class UdpServer {
protected DatagramPacket receivePacket;
protected DatagramPacket sendPacket;
public static void main(String args[]) throws IOException,
ClassNotFoundException {
UdpServer upd = new UdpServer();
DatagramSocket serverSocket = new DatagramSocket(9876);
DateFormat currentDate = new SimpleDateFormat("yyyy/MM/dd");
DateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
ByteArrayInputStream baos;
ObjectInputStream oos;
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (true) {
System.out.println("****************************************"
+ "\nServer is connected");
upd.receivePacket(serverSocket, receiveData);
String str = new String(upd.getData()).trim();
System.out.println("Message received is:" + " " + str);
if (str.equals("time")) {
str = currentTime.format(date);
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
} else if (str.equals("date")) {
str = currentDate.format(date);
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
} else if (str.equals("weather")) {
upd.receivePacket(serverSocket, receiveData);
str = upd.weather(str = new String(upd.getData()).trim());
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
} else if (str.equals("max")) {
byte[] buf = new byte[1024];
System.out.println("waitng for object to come");
upd.receivePacket(serverSocket, buf);
baos = new ByteArrayInputStream(buf);
oos = new ObjectInputStream(baos);
Object o = oos.readObject();
System.out.println(o);
} else {
str = "Unknown command, please try again..";
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
}
}
}
This is the error i get in the Server side
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 00000000
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at UdpServer.main(UdpServer.java:54)
Line 54 that the error indicates is this line on the server
baos = new ByteArrayInputStream(buf);
oos = new ObjectInputStream(baos);
If you could help me out of why this error is happening? thanx!

Your code creates alot of arrays it immediately discards. I would use a debugger to step through the code so you understand what it is doing.
private void receivePacket(DatagramSocket serverSocket, byte[] receiveData)
throws IOException {
// create a new array
byte[] rData = new byte[1024];
// throw away the orignal array so the new array will be update.
receiveData = rData;
// copy into the new array, not the old one.
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
}
In this case, the original receiveData will not me modified so it will contain lots of 0 bytes.
byte[] buf = new byte[bStream.toByteArray().length];
buf = bStream.toByteArray();
This creates three arrays when all you need is one. The first array bStream.toByteArray() is created just so you can determine what length it would be. You create a second array which is the same length but empty and put it in buf Finally you discard the second array and replace it with a copy of the first array.

Related

How to create an input stream whose source is the received packet (ByteArrayInputStream and DataInputStream)?

This is a portion of my code (Multicast subscriber to images)
public void subscribe() throws IOException {
byte[] b = new byte[100];
DatagramPacket datagram = new DatagramPacket(b, b.length, groupAddress, localPort);
MulticastSocket socket = new MulticastSocket(localPort);
socket.joinGroup(groupAddress);
socket.send(datagram);
while(true) {
socket.receive(datagram);
System.err.println("Received " + datagram.getLength() +
" bytes from " + datagram.getAddress());
datagram.setLength(b.length);
socket.leaveGroup(groupAddress);
socket.close();
}
Here is the task:
Create an input stream whose source is the received packet (e.g. ByteArrayInputStream and DataInputStream).
this is publisher:
private void castOneImage(DatagramSocket socket, String imageFn, SocketAddress groupSocketAddress) {
byte[] imageBytes = null;
try (InputStream in = getClass().getClassLoader().getResourceAsStream(imageFn);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream()) {
if (in == null) {
throw new FileNotFoundException("Cannot open image file " + imageFn);
}
int b;
while ((b = in.read()) != -1) {
byteOut.write(b);
}
imageBytes = byteOut.toByteArray();
byteOut.reset();
ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.SIZE / 8);
byteBuffer.putInt(imageBytes.length);
byteOut.write(byteBuffer.array());
byteOut.write(imageBytes);
imageBytes = byteOut.toByteArray();
DatagramPacket packet = new DatagramPacket(imageBytes, imageBytes.length, groupSocketAddress);
socket.send(packet);
} catch (IOException e) {
// if there is an error for this image, we soldier on hoping other images may be good
LOGGER.warn("I/O error: " + e.getMessage(), e);
}
}
Use a ByteArrayInputStream:
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(datagram.getData(), datagram.getOffset(), datagram.getLength()));
And move the close() outside the loop. You don't have to leave the group explicitly if you're about to close the socket.
EDIT To reconstitute the image data:
int length = dis.readInt();
byte[] image = new byte[length];
dis.readFully(image);
But of course as datagrams know their own length, you didn't really need to send or receive the length word at all.

File transfer (.png , .txt) between Server and Client using UDP

I wrote a server and client for client to connect to the server and select a data from the server's directory to transfer the data with UDP protocol but the problem is, it is only working for .txt files it isn't working for .png files and also in the .txt files the output files are not the same with the original one forexample lines between words are not there and all the words printed side by side instead of line by line. How can i fix this problem ?
Server side:
import java.io.*;
import java.net.*;
public class FTPServer {
public static void main(String[] args)
{
DatagramSocket socket = null;
DatagramPacket inPacket = null;
DatagramPacket outPacket = null;
byte[] inBuf, outBuf;
String msg;
final int PORT = 50000;
try
{
socket = new DatagramSocket(PORT);
while(true)
{
System.out.println("\nRunning...\n");
inBuf = new byte[1000];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
int source_port=inPacket.getPort();
InetAddress source_address = inPacket.getAddress();
msg = new String(inPacket.getData(), 0, inPacket.getLength());
System.out.println("CLient: " + source_address + ":" + source_port);
String dirname = "/home/erke/Desktop/data";
File f1 = new File(dirname);
File fl[] = f1.listFiles();
StringBuilder sb = new StringBuilder("\n");
int c=0;
for(int i = 0;i<fl.length;i++)
{
if(fl[i].canRead())
c++;
}
sb.append(c+ " files found.\n\n");
for(int i=0; i<fl.length;i++)
sb.append(fl[i].getName()+ " " + fl[i].length()+ " Bytes\n");
sb.append("\nEnter file name to Download: ");
outBuf = (sb.toString()).getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length, source_address, source_port);
socket.send(outPacket);
inBuf = new byte[1000];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String filename = new String(inPacket.getData(), 0, inPacket.getLength());
System.out.println("Requested File: " + filename);
boolean flis = false;
int index =-1;
sb = new StringBuilder("");
for(int i=0;i<fl.length;i++)
{
if(((fl[i].getName()).toString()).equalsIgnoreCase(filename))
{
index = i;
flis = true;
}
}
if(!flis)
{
System.out.println("ERROR");
sb.append("ERROR");
outBuf = (sb.toString()).getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length, source_address, source_port);
socket.send(outPacket);
}
else
{
try
{
//File send
File ff=new File(fl[index].getAbsolutePath());
FileReader fr = new FileReader(ff);
BufferedReader brf = new BufferedReader(fr);
String s = null;
sb=new StringBuilder();
while((s=brf.readLine())!=null)
{
sb.append(s);
}
if(brf.readLine()==null)
System.out.println("File Read Succesfull, CLosing Socket");
outBuf=new byte[100000];
outBuf = (sb.toString()).getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length,source_address, source_port);
socket.send(outPacket);
} catch (Exception ioe) {
System.out.println(ioe);
}
}
}
} catch (Exception e){
System.out.println("Error\n");
}
}
}
Client side:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class FTPClient {
public static void main(String[] args) {
DatagramSocket socket = null;
DatagramPacket inPacket = null;
DatagramPacket outPacket = null;
byte[] inBuf, outBuf;
final int PORT = 50000;
String msg = null;
Scanner src = new Scanner(System.in);
try
{
InetAddress address = InetAddress.getByName("127.0.0.1");
socket = new DatagramSocket();
msg = "";
outBuf =msg.getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length,address,PORT);
socket.send(outPacket);
inBuf = new byte[65535];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String data = new String(inPacket.getData(), 0, inPacket.getLength());
//Print file list
System.out.println(data);
//Send file name
String filename = src.nextLine();
outBuf = filename.getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length, address, PORT);
socket.send(outPacket);
//Receive file
inBuf = new byte[100000];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
data = new String(inPacket.getData(), 0, inPacket.getLength());
if(data.endsWith("ERROR"))
{
System.out.println("File doesn't exists.\n");
socket.close();
}
else
{
try
{
BufferedWriter pw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
pw.write(data);
//Force write buffer to Fİle
pw.close();
System.out.println("File Write Succesful. Closing Socket");
socket.close();
} catch (Exception ioe) {
System.out.println("File Error\n");
socket.close();
}
}
} catch (Exception e) {
System.out.println("\nNetwork Error. Try Again Later. \n");
}
}
}
In your code you are using String to store file data in both client and the server. In order to be able to transfer any file other then a text file, in your server you should have a byte[] buffer instead of String, and use it for loading file contents. You can do this by using classes with names ending with InputStream. After you do that send those bytes over a network. Same goes for the client.
InputStream and OutputStream are used to read\write bytes from files directly, while Reader and Writer classes are specifically intended to work with text files. You cannot read\write bytes with these classes, they work only with characters and strings. You will still be able to transfer text files too though since they are also just an array of bytes.
Also you should be using TCP if you want to transfer your files without losing packets, which UDP tends to do as it doesn't have mechanisms to ensure that packets are safely delivered to a destination like TCP does.

Why does this String.equals() not work?

I'm trying to build a simple UDPServer and UDPClient. A String comparison doesn't work.
Here's what I got so far:
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;
public class UDPSender
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9877);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
boolean weiter = true;
do {
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();
/*I'm trying to make the if()-statement true, but the program always enters the else()-clause, no matter what I do.*/
if("Shutdown".equals(sentence)) {
weiter = false;
String bye = ("Auf Wiedersehen! Verbindung wird gekappt...");
sendData = bye.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
serverSocket.close();
} else {
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
} while(weiter);
}
}
And this is the client:
import java.io.*;
import java.net.*;
import java.util.ArrayList;
class UDPClient{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
//Look, I'm explicitly sending Shutdown, too!
String sentence = "Shutdown";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9877);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
I would be happy if both would work on the same computer for now, but after this String issue is fixed, I need to get more PCs involved. Tried about every solution suggested in other similar questions on stackoverflow and anything google listed on the first three pages, nothing worked for me. Can you see something I can't?
The problem here is that you rely on the fixed size buffer byte[] ... = new byte[1024] to send and receive packets.
My advice is to send only the data you really need:
String sentence = "Shutdown";
byte[] sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9877);
... and create the String instance on the server side accordingly to the length obtained from the receivePacket.getLength() method:
String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
See also public String(byte[] bytes, int offset, int length)

ObjectInputStream giving strange results

Here is the code I am using.
Client:
public static void main(String[] args) throws IOException {
Socket socket = new Socket("0.0.0.0", 5555);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
FileInputStream in = new FileInputStream("C:/Documents and Settings/Owner/Desktop/Client/README.txt");
byte[] b = new byte[1024];
int i = 0;
i = in.read(b);
out.writeInt(i);
out.write(b, 0, i);
out.flush();
i = in.read(b);
out.writeInt(i);
out.write(b, 0, i);
out.flush();
out.close();
in.close();
socket.close();
}
Server:
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5555);
Socket s = ss.accept();
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
FileOutputStream fos = new FileOutputStream("C:/README.txt");
int i = 0;
i = in.readInt();
System.out.println(i);
byte[] bytes = new byte[i];
in.read(bytes);
i = in.readInt();
System.out.println(i);
byte[] bytes2 = new byte[i];
in.read(bytes2);
fos.write(bytes);
fos.close();
s.close();
ss.close();
}
The file README.txt has ~2400 bytes in it. When I run this, the server outputs this.
1024
1869488225
It then throws a java.lang.OutOfMemoryError.
Can anybody tell me why it is reading 1869488225 instead of 1024?
Thanks
in.read(bytes);
in.read(bytes2);
Here you are ignoring the return value of read and assuming that it fills the buffer. You should change read() to readFully() here, but in general you should never ignore a read() result. It can be -1 indicating EOS, or it can be any count from 1 up to the buffer size. If you inadvertently specify a zero length buffer it can even be zero.

UDP threading infinite loop in Java

I've written two programs. Now each program uses threading to send and receive packets at the same time.
Whenever I send packets from the server to the client, the message at the client ends gets received in an infinite loop. I.e; I've added a print statement that prints the message sent and this goes forever in an infinite loop. I want to make it so that it receives the message, and then be able to write back to the server and exit whenever the user wants to.
I've tried using socket.close(), but this makes it so that the client receives the message and I can only write back to the server once. After I send it, I can't send anymore. I want to make it so that I can write back more than once.
Can anyone please point me in the right direction?
My code is as follows;
public class UDPThreadClient extends Thread {
public static int port1;
//Create threaded server
UDPThreadClient (int port1) {
System.out.println ("Starting threaded client");
start();
}
public void run() {
int port = port1;
try {
DatagramSocket serverSocket = new DatagramSocket(port1);
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());
SocketAddress address = receivePacket.getSocketAddress();
System.out.println("RECEIVED from " + address + " : " + sentence);
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);
//serverSocket.close();
}
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
//Create client
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
port1 = Integer.parseInt(args[1]);
new UDPThreadClient (port1);
try {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
//clientSocket.close();
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
}
and
public class UDPThreadServer extends Thread {
public static int port1;
//Create threaded client
UDPThreadServer () {
System.out.println ("Starting threaded server");
start();
}
public void run() {
try {
DatagramSocket clientSocket = new DatagramSocket();
BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in));
Scanner in = new Scanner (inFromUser);
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte [1024];
byte[] receiveData = new byte [1024];
while (in.hasNextLine()) {
String sentence = in.nextLine();
//inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, port1);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket (receiveData, receiveData.length);
clientSocket.receive (receivePacket);
String modSentence = new String (receivePacket.getData());
System.out.println ("FROM SERVER: " + modSentence);
}
//clientSocket.close();
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
//Create server
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
port1 = Integer.parseInt(args[1]);
new UDPThreadServer ();
try {
DatagramSocket serverSocket = new DatagramSocket (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());
SocketAddress address = receivePacket.getSocketAddress();
System.out.println ("Received from " + address + " : " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
String capSentence = sentence.toUpperCase();
sendData = capSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
//serverSocket.close();
}
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
}
Thanks.
Looking at UDPClientServer:
When you create the Datagram packet, you give it the port to send it to, not the port that you are sending it from.
When I ran your code, nothing happened. The server is waiting on port port, while the client sends to port port1. If you instead send to port port (not accessible from the main method, but changing it to a field instead of local method would fix that, then the infinite looping occurs because the server sends a packet to the same port it is listening on. There's your problem. Do you supply the same numbers as the first and second arguments to your program?
From the server, you can use receivePacket.getPort() to get the port where the packet came from.
EDIT:
Your two classes have much repetition, which is probably a source of confusion. One class has a main which starts a client then creates a server type loop tester. The other class sets up a Server then creates a client type tester.
Below is only the class you've named UDPThreadServer with comments showing changes to make the server 'work' with the testing code in the main method. Note that the server should send to a port that it is not listening to. You are also reading port values from command line arguments. I just made up some numbers for the ports and stuck them in as constants.
public class UDPThreadServer extends Thread
{
public static int port1;
UDPThreadServer()
{
//server or client? it's hard to say. you call the socket a clientSocket.
System.out.println("Starting threaded server");
start();
}
public void run()
{
try
{
// Here client(?) is set up with empty constructor.
// It is a mystery what port it will get.
DatagramSocket clientSocket = new DatagramSocket();
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(inFromUser);
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (in.hasNextLine())
{
String sentence = in.nextLine();
// inFromUser.readLine();
sendData = sentence.getBytes();
// sending to port1? that must be the server.
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port1);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER: " + modSentence);
}
// clientSocket.close();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
}
// Create server
public static void main(String[] args)
{
// int port = Integer.parseInt(args[0]);
int port = 1927; // or whatever
// port1 = Integer.parseInt(args[1]);
port1 = 1928;
new UDPThreadServer();
try
{
// server resides on port1? if client sends to port 1, then this is so.
DatagramSocket serverSocket = new DatagramSocket(port1);
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());
SocketAddress address = receivePacket.getSocketAddress();
System.out.println("Received from " + address + " : " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
String capSentence = sentence.toUpperCase();
sendData = capSentence.getBytes();
// where did you get the info from? Client is set up with an empty constructor, so it is a mystery.
port = receivePacket.getPort();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
// serverSocket.close();
}
} catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}
Don't close the socket.
If that doesn't answer your question you need to clarify it.
while(true) is an infinite loop. Do you quit it in any case?

Categories