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.
Related
The task is to
(1) Send message from Client to Server via Bridge
(2) Send back the message in UPPER CASE from server to client via Bridge
(1) is done
I am have problem with sending the message back to the client
Here are the classes:
UDPCLIENT
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
//getting input from the user and sending to Bridge
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, 4000);
clientSocket.send(sendPacket);
//Getting data from the Bridge
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("C: FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
UDPSERVER
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(5000);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
//receiveing data from the bridge
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("S:RECEIVED: " + sentence);
InetAddress IPAddress = InetAddress.getByName("localhost");
// Sending data to the bridge
int port = 4000;
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Bridge
import java.io.*;
import java.net.*;
/**
* Write a description of class Bridge here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Bridge
{
public static void main(String args[]) throws Exception{
DatagramSocket bridgeSocket1 = new DatagramSocket(4000);
DatagramSocket bridgeSocket2 = new DatagramSocket();
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
DatagramPacket receivePacket;
DatagramPacket sendPacket;
InetAddress IPAddress = InetAddress.getByName("localhost");
while(true){
//Receiveing data from the UDPClient
receivePacket = new DatagramPacket(receiveData, receiveData.length);
bridgeSocket1.receive(receivePacket);
//Sending data to UDPServer
String sentence = new String(receivePacket.getData());
System.out.println("B: Data Received:" + sentence);
int port = 5000;
sendData = sentence.getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
bridgeSocket2.send(sendPacket);
// Receiving Data from the UDPServer
receivePacket = new DatagramPacket(receiveData,receiveData.length);
bridgeSocket1.receive(receivePacket);
String capitalizedSentence = new String(receivePacket.getData());
System.out.println("Capitalized Sentence in the Bridge Class: " + capitalizedSentence);
//Sending data to the UDPClient
sendData = capitalizedSentence.getBytes();
sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,5000);
bridgeSocket2.send(sendPacket);
}
}
}
You are sending the response from the server back to the server because you are using port 5000 as the destination port. But the server is running on 5000, not your client. You have to assign your client to a port as well and send the message received from the server back to the client on the defined port.
For now your sequence looks like this:
(C) ---> 4000
---> 5000
4000 <---
---> 5000
4000 <---
---> 5000
4000 <---
---> 5000
4000 <---
[...]
But it should look like this:
(C) ---> 4000
---> 5000
4000 <---
4500 <---
(assuming your client is listening on port 4500)
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.
I want to make three servers communicate using java UDP. If a particular method which exists for all the three servers is called on the first server instance the other two servers should also communicate the result for those methods to the first servers using UDP. Should I be using multicast ? I tried using Unicast but its not working out.
UDPDataExchangeclass
import java.io.BufferedReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class UDPDataExchange {
String Hostname;
static InetAddress IPAddress;
UDPDataExchange() {
Hostname = new String("127.0.0.1");
try {
IPAddress = InetAddress.getByName(Hostname);
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void requestData(int portNumber, String data) {
try {
DatagramSocket clientSocket = new DatagramSocket();
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
byte[] sendData = new byte[1024];
sendData = data.getBytes();
System.out.print("Ready to send data ");
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, portNumber);
clientSocket.send(sendPacket);
clientSocket.setSoTimeout(10000);
try {
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
InetAddress returnIPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println("From server at: " + returnIPAddress + ":"
+ port);
System.out.println("Message: " + modifiedSentence);
}
catch (SocketTimeoutException ste) {
System.out.println("Timeout Occurred: Packet assumed lost");
}
//clientSocket.close();
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void responseData(int portNumber) {
try {
DatagramSocket serverSocket = new DatagramSocket(portNumber);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
System.out.println("Waiting for datagram packet");
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println("From: " + IPAddress + ":" + port);
System.out.println("Message: " + sentence);
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
catch (SocketException ex) {
System.out.println("UDP Port 9876 is occupied.");
System.exit(1);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
UDPTest
import java.io.*;
import java.net.*;
class UDPTest extends UDPDataExchange {
public static void main(String args[]) throws Exception {
int UDPClientConcordiaPortNumber = 9876;
int UDPClientMcgillPortNumber=9890;
int UDPClientDawsonPortNumber=9891;
UDPTest McgillServer=new UDPTest();
UDPTest DawsonServer=new UDPTest();
McgillServer.responseData(UDPClientConcordiaPortNumber);
DawsonServer.responseData(UDPClientDawsonPortNumber);
UDPTest concordiaTest = new UDPTest();
System.out.println("Attemping to connect to " + IPAddress
+ ") via UDP port" + UDPClientConcordiaPortNumber);
String concordiaData = "Hello from concordia";
System.out.println("Sending data " + concordiaData.length()
+ " bytes to server.");
concordiaTest.requestData(UDPClientConcordiaPortNumber, concordiaData);
}
}
In the UDPDataExchange I've defined two methods to send and receive data. In the UDPTest class I am trying to create two server instances namely mcgill and dawson server who would listen to concordia's port for data sent. Once they receive it they send a response back to Concordia
Try this, I´m not sure if it is exactly what you want.
UDPDataExchange
public class UDPDataExchange {
String Hostname;
static InetAddress IPAddress;
UDPDataExchange() {
Hostname = new String("127.0.0.1");
try {
IPAddress = InetAddress.getLocalHost();
} catch (final UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void requestData(final int portNumber, final String data) {
try {
final DatagramSocket clientSocket = new DatagramSocket();
final byte[] receiveData = new byte[1024];
final DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
byte[] sendData = new byte[1024];
sendData = data.getBytes();
System.out.print("Ready to send data ");
final DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, portNumber);
clientSocket.send(sendPacket);
clientSocket.setSoTimeout(10000);
try {
clientSocket.receive(receivePacket);
final String modifiedSentence = new String(receivePacket.getData());
final InetAddress returnIPAddress = receivePacket.getAddress();
final int port = receivePacket.getPort();
System.out.println("From server at: " + returnIPAddress + ":"
+ port);
System.out.println("Message: " + modifiedSentence);
} catch (final SocketTimeoutException ste) {
System.out.println("Timeout Occurred: Packet assumed lost");
}
// clientSocket.close();
} catch (final SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void responseData(final int portNumber) {
try {
final DatagramSocket serverSocket = new DatagramSocket(portNumber, IPAddress);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
receiveData = new byte[1024];
final DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
System.out.println("Waiting for datagram packet");
serverSocket.receive(receivePacket);
final String sentence = new String(receivePacket.getData());
final InetAddress IPAddress = receivePacket.getAddress();
final int port = receivePacket.getPort();
System.out.println("From: " + IPAddress + ":" + port);
System.out.println("Message: " + sentence);
final String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
final DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
} catch (final SocketException ex) {
System.out.println("UDP Port 9876 is occupied.");
System.exit(1);
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
UDPTest
class UDPTest extends UDPDataExchange {
public static void main(final String args[]) throws Exception {
final int UDPClientConcordiaPortNumber = 9876;
final int UDPClientMcgillPortNumber = 9890;
final int UDPClientDawsonPortNumber = 9891;
final UDPTest McgillServer = new UDPTest();
final UDPTest DawsonServer = new UDPTest();
final Thread t1 = new Thread() {
#Override
public void run() {
McgillServer.responseData(UDPClientMcgillPortNumber);
}
};
t1.setDaemon(true);
t1.start();
final Thread t2 = new Thread() {
#Override
public void run() {
DawsonServer.responseData(UDPClientDawsonPortNumber);
}
};
t2.setDaemon(true);
t2.start();
final UDPTest concordiaTest = new UDPTest();
System.out.println("Attemping to connect to " + IPAddress
+ ") via UDP port" + UDPClientConcordiaPortNumber);
final String concordiaData = "Hello from concordia";
System.out.println("Sending data " + concordiaData.length()
+ " bytes to server.");
concordiaTest.requestData(UDPClientMcgillPortNumber, concordiaData);
concordiaTest.requestData(UDPClientDawsonPortNumber, concordiaData);
}
}
I´ll explain brielfy what I changed:
UDPDataExchange:
I changed the IPAdress to InetAddress.getLocalHost()
UDPTest:
Each call to responseData runs in a separate Thread, to avoid blocking the main thread.
That threads are daemon to allow exit application.
The requestData() invocation has changed to call each server.
Hope to be useful.
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 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