I was parsing a string into 2 parts partitioned by the 1st appearance of the '&' character. For example: if the string is 555&hello &world the partitions will be 555 and hello &world. I used following code:
String[] numberAndMessage=currentMessage.split("(\\&)",2);
System.out.println(numberAndMessage[1]+storedMessage.message+"end");
So, with input: 555&hello &world
The output I expected was: hello &worldend
But instead it gave: hello &world
Maybe any problem in the ending character of 2nd partition.
But what is the problem?
The code:
UDPServer.java:
import java.net.*;
public class UDPServer extends Thread{
public void run(){
try{
DatagramSocket serverSocket = new DatagramSocket(9999);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String currentMessage = new String( receivePacket.getData());
System.out.println("RECEIVED: " + currentMessage);
String[] numberAndMessage=currentMessage.split("(\\&)", 2);
System.out.println("noAndMessage[0]="+numberAndMessage[0]+";noAndMessage[1]="+numberAndMessage[1]);
System.out.println("numberAndMessage[1]= "+numberAndMessage[1]+"end");
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception
{
UDPServer server=new UDPServer();
server.start();
}
}
UDPClient.java:
import java.io.*;
import java.net.*;
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];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9999);
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();
}
}
Input at UDPClient.java:
555&hello world
Output at UDPServer.java:
RECEIVED: 555&hello world
noAndMessage[0]=555;noAndMessage[1]=hello world
numberAndMessage[1]= hello world
i dont know about storedMessage.message .but following code works good for you expecting output.
String currentMessage="555&hello &world";
String[] numberAndMessage=currentMessage.split("(\\&)",2);
System.out.println(numberAndMessage[1]+"end");
here you will get OUtPUT:
hello &worldend
Try this
public class Test {
public static void main(String[] args) {
String currentMessage = "555&hello &world";
String[] numberAndMessage = currentMessage.split("(\\&)", 2);
System.out.println(numberAndMessage[1] + "end");
}
}
output
hello &worldend
for your full code I got this following result
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServer extends Thread{
public void run(){
try{
DatagramSocket serverSocket = new DatagramSocket(9999);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
String a = "555&hello world";
receiveData = a.getBytes();
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
//serverSocket.receive(receivePacket);
String currentMessage = new String( receivePacket.getData());
System.out.println("RECEIVED: " + currentMessage);
String[] numberAndMessage=currentMessage.split("(\\&)", 2);
System.out.println("noAndMessage[0]="+numberAndMessage[0]+";noAndMessage[1]="+numberAndMessage[1]);
System.out.println("numberAndMessage[1]= "+numberAndMessage[1]+"end");
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception
{
UDPServer server=new UDPServer();
server.start();
}
}
Output is
RECEIVED: 555&hello world
noAndMessage[0]=555;noAndMessage[1]=hello world
numberAndMessage[1]= hello worldend
Related
I create a small demo, which has the function is :
- In UDPClient:
+ user input two sentence : sentenceA and sentenceB
+ than pass them to UDPServer
- In UDPServer :
+ those two sentences will be
capitalized
+ pass those two capitalized sentences back to UDPClient
The problem is, when I pass two sentence from UDPClient to UDPServerFor example: "aa" and "bb" . So, in UDPServer I can exactly get "aa" and "bb" . But when I return capitalized sentences : "AA" and "BB" from UDPServer to UDPClient, I can only get "AA". How do I get exactly both "AA" and "BB" in UDPClient after the processing ?
Here is my code :
UDP Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
public class UDPClient extends Thread {
static int port = 1234;
public UDPClient() {
}
#Override
public void run() {
super.run();
while (true) {
try {
DatagramSocket clientSocket = new DatagramSocket(5678);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] sendData1 = new byte[1024];
byte[] receiveData = new byte[1024];
System.out.println("\nInput sentenceA : " );
String sentence = inFromUser.readLine();
System.out.println("Input sentenceB : " );
String sentence1 = inFromUser.readLine();
sendData = sentence.getBytes();
sendData1 = sentence1.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 1234);
clientSocket.send(sendPacket);
DatagramPacket sendPacket1 = new DatagramPacket(sendData1, sendData1.length, IPAddress, 1234);
clientSocket.send(sendPacket1);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentenceA = new String(receivePacket.getData());
String modifiedSentenceB = new String(receivePacket.getData());
System.out.println("FROM SERVER : " + " sentenceA : " + modifiedSentenceA + ", sentenceB : " + modifiedSentenceB);
clientSocket.close();
} catch (SocketException ex) {
System.out.println(ex);;
} catch (UnknownHostException ex) {
System.out.println(ex);;
} catch (IOException ex) {
System.out.println(ex);
}
}
}
public static void main(String[] args) throws SocketException {
Thread t = new UDPClient();
t.start();
}
}
UDPServer :
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPServer extends Thread{
public UDPServer(){
}
#Override
public void run() {
super.run(); //To change body of generated methods, choose Tools | Templates.
try {
DatagramSocket serverSocket = new DatagramSocket(1234);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
byte[] sendData1 = new byte[1024];
while(true){
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
String sentence1 = new String(receivePacket.getData());
System.out.println("RECEIVED " + sentence + " sentence1 : " + sentence1);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
String b = sentence1.toUpperCase();
sendData = capitalizedSentence.getBytes();
sendData1 = b.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
DatagramPacket sendPacket1 = new DatagramPacket(sendData1, sendData1.length, IPAddress, port);
serverSocket.send(sendPacket1);
}
} catch (SocketException ex) {
System.out.println(ex);;
} catch (IOException ex) {
System.out.println(ex);;
}
}
public static void main(String[] args){
Thread serverThead = new UDPServer();
serverThead.start();
}
}
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentenceA = new String(receivePacket.getData());
String modifiedSentenceB = new String(receivePacket.getData());
Your client is only executing one receive. You're printing the received packet twice, but it's the same packet.
I am currently working on a small peer to peer application in which users can chat with each other within a LAN. I have currently implemented the following code to broadcast by a user that s/he is online.
import java.io.*;
import java.net.*;
class BroadcastOnline extends Thread{
public void run(){
try{
String string = "a";
DatagramSocket serverSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("255.255.255.255");
byte[] sendData = new byte[1];
sendData = string.getBytes();
for(;;){
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9877);
serverSocket.send(sendPacket);
Thread.sleep(1000);
}
} catch (Exception e){}
}
}
And I have used following code to find who are online.
import java.io.*;
import java.net.*;
class FindUsers {
InetAddress ad;
String ipaddress;
String onlineUsers[] = new String [10];
FindUsers() throws Exception{
DatagramSocket clientSocket = new DatagramSocket(9877);
int count=0;
byte[] receiveData = new byte[1];
for(int i=0;i<=9;i++){
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
ad = receivePacket.getAddress();
ipaddress = ad.getHostAddress();
onlineUsers[i]=ipaddress;
count++;
}
}
}
But the problem is that the above codes are running in infinite loop. And I think the implementation is a bit silly.
Are there any other ways to implement this feature?
EDIT:
I got the solution to list IP addresses in the list.
How can I get and keep the user friendly names in the list?
You need to broadcast the name like following in the BroadcastOnline class:
byte[] sendData = new byte[15];
String name = nameField.getText();
sendData = name.getBytes();
for(;;){
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9877);
serverSocket.send(sendPacket);
Thread.sleep(1000);
}
**of course it is needed to catch exception above
And to find users who are online, implement the following code.
import java.io.*;
import java.net.*;
import java.util.List;
import java.util.ArrayList;
public class FindUsers{
InetAddress inetAddress;
List<String> ipList = new ArrayList<String>();
List<String> nameList = new ArrayList<String>();
String ipAddress;
String name;
DatagramSocket clientSocket;
DatagramPacket receivePacket;
int count=0;
byte[] receiveData;
long futureTime;
Thread collect;
boolean refresh = true;
public FindUsers(){
futureTime = System.currentTimeMillis()+1100;
try{
clientSocket = new DatagramSocket(9877);
}
catch(IOException e){
e.printStackTrace();
System.out.println(e.toString());
}
collect = new Thread(new Runnable(){
public void run(){
for(;;){
receiveData = new byte[15];
receivePacket = new DatagramPacket(receiveData, receiveData.length);
try{
clientSocket.receive(receivePacket);
inetAddress = receivePacket.getAddress();
ipAddress = inetAddress.getHostAddress();
}
catch(IOException e){
//e.printStackTrace();
}
if(!ipList.contains(ipAddress)){
name = new String( receivePacket.getData());
ipList.add(ipAddress);
nameList.add(name);
receiveData = null;
}
try{
Thread.sleep(10);
}
catch(InterruptedException e){
//System.out.println("\nInterrupted!");
return;
}
}
}
});
collect.start();
while(System.currentTimeMillis()<=futureTime){
//do nothing.
}
clientSocket.close();
collect.interrupt();
int size = nameList.size();
if (size==0){
System.out.println("No online servers.");
}
else{
for(int i = 0; i< nameList.size();i++){
System.out.println(nameList.get(i)+ ": "+ ipList.get(i));
}
}
}
public static void main(String[] args){
FindUsers f = new FindUsers();
}
}
Hope this will help.
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.
I'm writing a client-server chat program using UDP. If either the client or the server sends a message, and the next message they send is shorter than the previous one they sent, part of the longer message will be put onto the end of the shorter one. This is my first time using UDP and I've no idea what could be causing this, I made a similiar program using TCP and didn't have this issue.
What the client sees:
Client: Hello, how are you?
Server: I'm good thanks, and you?
Client: Great
What the server sees:
Client: Hello, how are you?
Server: I'm good thanks, and you?
Client: Great, how are you?
My server code:
public class ChatServer implements Runnable
{
public static void main(String[] args) throws Exception
{
new Thread(new ChatServer()).start();
}
#Override
public void run()
{
try
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[65508];
byte[] sendData = new byte[65508];
System.out.println("Enter a username: ");
String serverUsername = inFromUser.readLine();
System.out.println("Send message...");
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String clientSentence = new String(receivePacket.getData());
System.out.println(clientSentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.print("Me: ");
String serverSentence = serverUsername + ": " + inFromUser.readLine();
sendData = serverSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
catch (IOException ex)
{
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
My client code:
public class ChatClient
{
public static void main(String[] args) throws Exception
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
try (DatagramSocket clientSocket = new DatagramSocket())
{
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[65508];
byte[] receiveData = new byte[65508];
System.out.println("Enter a username: ");
String clientUsername = inFromUser.readLine();
System.out.println("Send message...");
while(true)
{
System.out.print("Me: ");
String clientSentence = clientUsername + ": " + inFromUser.readLine();
sendData = clientSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String serverSentence = new String(receivePacket.getData());
System.out.println(serverSentence);
}
}
catch(Exception e)
{
e.getMessage();
}
}
}
Receive Packet is initially null terminated.
It gets filled in with the network data.
You need to tell the string how many bytes to read or zero out receiveData after each construction of clientSentence. Using the length of the packet is the correct way to approach this.
Change:
String clientSentence = new String(receivePacket.getData());
To:
String clientSentence = new String(receivePacket.getData() ,0 , receivePacket.getLength());
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.