Need som help with UDP code
Hello everyone,
I am new to the forum and was wondering if anyone had some insight into a problem I am having with some code?
I am creating a UDP server/client that seems to work network wise, however when a second message is sent to the server, the original message still is in the buffer. For instance, when I start with a fresh launch of the server and client I can enter "Hello world" in the client and it shows on the server as "Hello World". However if I send through "nice" as a second transmission, the server reports "niceo world" It seems that some sort of buffer is not getting cleared out. Is there a way to do this?
Here is my server code:
Code:
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(7777);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
byte[] killByte = new byte[0];
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 capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
receivePacket.setData(killByte);
}
}
}
Here is my client code:
Code:
import java.io.*;
import java.net.*;
class UDPClient3
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
byte[] b = new byte[] {(byte)65, (byte)101, (byte)23, (byte)253};
InetAddress IPAddress = InetAddress.getByAddress(b);
System.out.println("Enter Text:");
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7777);
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();
}
}
The problem continues until I relaunch the server, so it must be on the server side.
Any help would be much appreciated