Multiple Clients in UDP server - java

I wrote this code to recive data from a client via socket
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(12890);
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 capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
But if I try to launch another Client it don't work , look like if the server is blocked. How can I change the code to let the server communicating with more then one client

You are looking for a concurrent server. A concurrent server basically creates a child process for each client. Here is a basic way to do in java http://www.how2java.com/2012/05/how-to-create-concurrent-server-using.html

Related

Java Socket Programming (Client,Bridge,Server)

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)

How to get UDP server to respond to a UDP client packet?

I'm having trouble getting the server to send data back to the client. Here is my code and my inputs and results.
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 {
InetAddress ip = InetAddress.getByName("127.0.0.1");
int port = 1345;
//Creates connection socket.
DatagramSocket serverSocket = new DatagramSocket(port);
System.out.println("Server Active");
while(true) {
//Receiving packet
byte[] buffer = new byte[100];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
String clientInput = new String(buffer);
System.out.println("Server has Received : " + clientInput);
//Sending packet
byte[] data = clientInput.getBytes();
DatagramPacket sendPack = new DatagramPacket(data, data.length, ip, port);
serverSocket.send(sendPack);
String serverInput = new String(data);
System.out.println("Server has sent: " + serverInput);
}
}
}
~~~~~~~~~~~~~~~~~
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramSocket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
public class UDPClient
{
public static void main(String args[]) throws IOException
{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress ip = InetAddress.getByName("127.0.0.1");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
int port = 1345;
System.out.println("Would you like to continue?");
while(inFromUser.readLine().equals("Yes") || inFromUser.readLine().equals("yes")) {
System.out.println("Enter an expression to be evaluated");
//gets userInput
String userInput = inFromUser.readLine();
byte[] buffer = userInput.getBytes();
//sends packet to server
DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, ip, port);
clientSocket.send(sendPacket);
System.out.println("Client has sent: " + userInput);
//receives packet from server
byte[] data = new byte[100];
DatagramPacket receivePacket = new DatagramPacket(data, data.length);
clientSocket.receive(receivePacket);
String serverInput = new String(data);
System.out.println("Client has received: " + serverInput);
System.out.println("Would you like to continue?");
}
}
}
I am not sure why the server does not echo back to the client? I'm not sure what I am doing wrong, or about the overall quality of this code.
The server is sending the reply to itself. When you create the sendPacket in the server, you're giving it ip and port but the ip and port are the server's own IP and bound (listening) port, not the port of your client.
Because the client created its DatagramSocket without specifying a port, the system will dynamically choose an unused port number for it. You need to obtain the client's port number with receivePacket.getSocketAddress() (in the server), then use that address in your construction of sendPacket. In fact, there is an alternate constructor for DatagramPacket that accepts buffer, length and SocketAddress which is ideal for constructing the reply packet.

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);
}
}

Java UDP Chat Program: Part of first message gets appended onto second

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());

Sending and receiving UDP packets?

I have made a program to send an UDP packets from a client to a server.
Here is the transmitter code:
import java.io.IOException;
import java.net.*;
public class JavaApplication9 {
public static void main(String[] args) throws UnknownHostException, SocketException, IOException {
// TODO code application logic here
byte[] buffer = {10,23,12,31,43,32,24};
byte [] IP = {-64,-88,1,106};
InetAddress address = InetAddress.getByAddress(IP);
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, address, 57
);
DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.send(packet);
System.out.println(InetAddress.getLocalHost().getHostAddress());
}
}
The receiver code function is this:
public void run() {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
byte[] sendData = new byte[8];
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();
String sendString = "polo";
sendData = sendString.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
I have used the Wireshark program. The UDP packet is received in the Wireshark program at the receiver but the Java program wouldn't recognize it, the program just keeps listening to the port and nothing happens?
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging, try listening on port > 1024 (e.g. 5000 or 9000). Ports < 1024 are normally used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check to prevent such a situation.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}

Categories

Resources