I want to create a datagram server/client program where the server picks a random string from an array and send it to the client. But when i run the server and then the client which sends data about the buf byte array. The client sends the data to the serve as I understand but the server doesn't receive it.
Here's the client code:
import java.io.*;
import java.net.*;
import java.util.*;
public class SDClient {
protected static String labelText;
public static void main(String[] args) throws IOException {
//socket setup
MulticastSocket socket = new MulticastSocket(1);
System.out.println("socket opened");
InetAddress group = InetAddress.getByName("230.0.0.0");
socket.joinGroup(group);
System.out.println("socket joined group");
//packet setup
DatagramPacket packet;
byte[] buf = new byte[256];
//send packet
packet = new DatagramPacket(buf, buf.length);
packet.setAddress(group);
packet.setPort(2);
socket.send(packet);
System.out.println("packet sent to: ");
System.out.println("Port: " + packet.getPort() + " Address: " + packet.getAddress());
//receive packet
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("packet received");
//display packet string
labelText = new String(packet.getData(), 0, packet.getLength());
System.out.println("label text: " + labelText);
socket.leaveGroup(group);
socket.close();
}
}
here's the server code:
import java.io.*;
import java.net.*;
import java.util.*;
public class SDServerThread extends Thread {
protected DatagramSocket socket = null;
protected String[] labelText = {"Packet sent and received", "Hello World!", "It works."};
public SDServerThread() throws IOException {
this("SDServerThread");
}
public SDServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(2);
System.out.println("socket opened");
}
public void run() {
try {
byte[] buf = new byte[256];
DatagramPacket packet = null;
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("packet received");
String getText = getText();
buf = getText.getBytes();
InetAddress group = InetAddress.getByName("230.0.0.0");
packet = new DatagramPacket(buf, buf.length, group, 1);
socket.send(packet);
System.out.println("packet sent");
} catch (IOException e) {
e.printStackTrace();
}
}
private String getText() {
int textNr = (int)(Math.random() * 3);
String returnT = labelText[textNr];
return returnT;
}
}
Thanks in advence
I fixed it by making the servers DatagramSocket into a MulticastSocket and then made it join the group the client is in.
public class SDServerThread extends Thread {
protected MulticastSocket socket = null;
...
socket = new MulticastSocket(2);
...
socket.joinGroup(group);
}
Related
What i'm trying to do is group 2 clients and make them communicate with eachother. So if 2 clients are connected they would only be able to communicate with eachother and if a third client got connected it would not be able to communicate with the 2 other clients but it would create another group of 2 clients and so on... Right now if a client sends a message it send it over to all clients but i don't know how to make it work like described above. Messages are send from client by typing something in console.
server:
public class Server extends Thread{
public final static int PORT = 7331;
private final static int BUFFER = 1024;
private DatagramSocket socket;
private ArrayList<InetAddress> clientAddresses;
private ArrayList<Integer> clientPorts;
private HashSet<String> existingClients;
public Server() throws IOException {
socket = new DatagramSocket(PORT);
System.out.println("[SERVER] UDP server successfully launched on port " + PORT);
clientAddresses = new ArrayList<InetAddress>();
clientPorts = new ArrayList<Integer>();
existingClients = new HashSet<String>();
}
public void run() {
byte[] buf = new byte[BUFFER];
while (true) {
try {
//resets buffer so only new messages get displayed
Arrays.fill(buf, (byte) 0);
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String content = new String(buf, buf.length);
InetAddress clientAddress = packet.getAddress();
int clientPort = packet.getPort();
String id = clientAddress.toString() + "," + clientPort;
if (!existingClients.contains(id)) {
existingClients.add(id);
clientPorts.add(clientPort);
clientAddresses.add(clientAddress);
}
System.out.println(id + " : " + content);
byte[] data = (id + " : " + content).getBytes();
for (int i = 0; i < clientAddresses.size(); i++) {
InetAddress cl = clientAddresses.get(i);
int cp = clientPorts.get(i);
packet = new DatagramPacket(data, data.length, cl, cp);
socket.send(packet);
}
} catch (Exception e) {
System.err.println(e);
}
}
}
public static void main(String args[]) throws Exception {
Server s = new Server();
s.start();
}
}
clients:
public class Client implements Runnable {
public static void main(String args[]) throws Exception {
String host = "127.0.0.1";
DatagramSocket socket = new DatagramSocket();
//handles the receiving part for every client (incoming packets to clients)
MessageReceiver r = new MessageReceiver(socket);
Client s = new Client(socket, host);
Thread rt = new Thread(r);
Thread st = new Thread(s);
rt.start();
st.start();
}
public final static int PORT = 7331;
private DatagramSocket sock;
private String hostname;
Client(DatagramSocket s, String h) {
sock = s;
hostname = h;
}
//sending clients socket to server
private void sendMessage(String s) throws Exception {
//getting bytes from message
byte buf[] = s.getBytes();
//getting hostname from server
InetAddress address = InetAddress.getByName(hostname);
//setting up packet
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
//sending packet to server
sock.send(packet);
}
public void run() {
//connected boolean is used to send a greetings message once for every new client that has joined
boolean connected = false;
do {
try {
sendMessage("GREETINGS");
connected = true;
} catch (Exception e) {
}
} while (!connected);
//reads from the console
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
while (!in.ready()) {
Thread.sleep(100);
}
//sends message from console to server
sendMessage(in.readLine());
} catch (Exception e) {
System.err.println(e);
}
}
}
}
//this class handles receiving part of clients
class MessageReceiver implements Runnable {
DatagramSocket sock;
byte buf[];
MessageReceiver(DatagramSocket s) {
sock = s;
buf = new byte[1024];
}
public void run() {
while (true) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
sock.receive(packet);
String received = new String(packet.getData(), 0,
packet.getLength());
System.out.println(received);
} catch (Exception e) {
System.err.println(e);
}
}
}
}
What youre trying is a message broadcast or a message-repeater-client.
broadcasting is implemented on network layer (using brodcast the local network broadcast adress).
And if you implementing it that way, you'll flood your network, when you have more than 2 clients. Best regards to your network admin. ;-)
I need to write a Java program that can catch UDP packets. I wrote a basic UDP Receiver program but I am unsure how to adjust it for this purpose.
import java.io.*;
import java.net.*;
public class BasicReceiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new BasicReceiver().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
InetAddress IPAddress = receivePacket.getAddress();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
I am not receiving any packets but I can see packets on my Ethernet Port:
WireShark Snapshot
1) I am able to input and send my file name from my client to my server. but once it reaches my server I am unable to access the file even though the location and name of the file is correct.
2) since I am limited to 1500 bytes per transmission, I have to send my data in small 1500 byte packets. but I am facing problems sending data with more than 1500 bytes. this could also be because I am using a byte array.
3) I am unable to convert the mp3 file that I have read and converted to bytes back to an mp3 file
I have tried using other files to see if I made a mistake, but no matter what kind of file I use the result is always the same.
import java.io.*;
import java.net.*;
import java.util.*;
class UDPClientThreads {
public static void main(String args[]) throws Exception
{
String ul;
Scanner cin = new Scanner(System.in);
System.out.print("Enter uname: ");
ul = cin.nextLine();
long tstart = System.currentTimeMillis();
DatagramSocket clientSocket=new DatagramSocket();
InetAddress IPAddress=InetAddress.getByName("localhost");
byte[] sendData=new byte[1500];
byte[] receiveData=new byte[1500];
System.out.println("sent: "+ul);
sendData=ul.getBytes();
DatagramPacket sendPacket=
new DatagramPacket(sendData, sendData.length,IPAddress, 12313);
clientSocket.send(sendPacket);
DatagramPacket receivePacket=
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
System.out.println(receivePacket.getData().length);
clientSocket.close();
}
}
import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.file.Files;
public class UDPServerThreads {
public class UDPClientHandler1 implements Runnable {
byte[] bytesFromFile;
InetAddress address;
int port;
public UDPClientHandler1(byte[] bytesFromFile, InetAddress address, int port) {
this.bytesFromFile=bytesFromFile;
this.address=address;
this.port=port;
}
public void run() {
byte[] sendData=new byte[1500];
try{
String threadName =
Thread.currentThread().getName();
String message="in HandleClient";
long cstarttime = System.currentTimeMillis();
System.out.println("before csocket");
DatagramSocket csocket=new DatagramSocket();
sendData= bytesFromFile;
DatagramPacket sendPacket=
new DatagramPacket(sendData, sendData.length, address, port);
csocket.send(sendPacket);
System.out.println("after send in thread "+"IPAddress="+address+" port="+port);
long cendtime = System.currentTimeMillis();
System.out.println("time="+(cendtime-cstarttime));
}
catch (IOException e) {}
}
}
public void nonStatic(byte[] bytesFromFile, InetAddress address, int port) {
Thread t = new Thread(new UDPClientHandler1(bytesFromFile,address,port));
t.start();
}
public static void main(String args[]) throws Exception
{
UDPServerThreads udpserver= new UDPServerThreads();
try {
DatagramSocket serverSocket=new DatagramSocket(12313);
byte[] receiveData=new byte[1500];
int count=0;
while(true)
{
DatagramPacket receivePacket=
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
System.out.println("after rcv in server");
String udpmessage=new String(receivePacket.getData());
System.out.println("sentence"+udpmessage);
try
{
File f = new File(udpmessage);
byte[] bytesFromFile = Files.readAllBytes(f.toPath());
System.out.println(bytesFromFile.length);
InetAddress address=receivePacket.getAddress();
int port=receivePacket.getPort();
udpserver.nonStatic(bytesFromFile,address,port);
count++;
System.out.println("after start thread"+count);
}
catch(Exception e)
{
System.out.println("not working");
}
}
}
catch (IOException e) {}
}
}
At the end I expect my server to send the mp3 file to my client then my client will create an mp3 file that can be opened and played.
I am making a peer to peer chat application for which I have written the below code for chat with one person. This code works for localhost(127.0.0.1) but doesn't work for any specific ip address(192.168.43.118) and throws bindexception. Please help.
import java.sql.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class communicate {
public static void main(String args[]) throws Exception {
communicate ob = new communicate();
String ip = "192.168.43.118";
ob.text(ip);
}
public void text(String friend_ip) throws Exception{
System.out.println("Press 'Exit' to exit the chat");
int send_port = 40002;
int receive_port = 40002;
//InetAddress inetaddr = InetAddress.getByName(friend_ip);
byte[] ipAddr = new byte[] { (byte)192, (byte)168, (byte)43, (byte)118 };
System.out.println(ipAddr.length);
InetAddress inetaddr = InetAddress.getByAddress(ipAddr);
System.out.println("B");
DatagramSocket serverSocket = new DatagramSocket(receive_port, inetaddr);
System.out.println("YO");
Runnable send = new SendMsg(send_port, friend_ip, serverSocket);
Runnable receive = new GetMsg(friend_ip, receive_port, serverSocket);
Thread t1 = new Thread(send);
Thread t2 = new Thread(receive);
t1.start();
t2.start();
}
class SendMsg implements Runnable {
private DatagramSocket senderSocket;
private int send_port;
private String sendto_ip;
SendMsg(int port, String friend_ip, DatagramSocket ds)throws Exception {
senderSocket = new DatagramSocket(64432);
send_port = port;
sendto_ip = friend_ip;
}
public void run(){
try {
while(true) {
String sendString;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
sendString = br.readLine();
byte[] sendData = sendString.getBytes();
byte[] ipAddr = new byte[] { (byte)192, (byte)168, (byte)43, (byte)118 };
InetAddress inetAddress = InetAddress.getByAddress(ipAddr);
DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, inetAddress, send_port);
senderSocket.send(sendPacket);
System.out.println("Message Sent");
}
}
catch(Exception e) {
System.out.println("Exc at Sender\n" + e);
}
finally {
if(senderSocket != null) senderSocket.close();
}
}
}
class GetMsg implements Runnable{
private DatagramSocket serverSocket;
private String friend_ip;
private int receive_port;
GetMsg(String ip, int port, DatagramSocket ds) throws Exception{
friend_ip = ip;
receive_port = port;
serverSocket = ds;
}
public void run(){
try {
while(true) {
byte[] receiveData = new byte[10000];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String message = new String (receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(friend_ip + ": " + message);
}
}
catch(Exception e) {
System.out.println("Exc at Rec\n" + e);
}
finally {
if(serverSocket != null) serverSocket.close();
}
}
}
}
When I run it on terminal the following output is shown
Press 'Exit' to exit the chat
4
B
Exception in thread "main" java.net.BindException: Cannot assign requested address (Bind failed)
at java.base/java.net.PlainDatagramSocketImpl.bind0(Native Method)
at java.base/java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:131)
at java.base/java.net.DatagramSocket.bind(DatagramSocket.java:394)
at java.base/java.net.DatagramSocket.<init>(DatagramSocket.java:244)
at java.base/java.net.DatagramSocket.<init>(DatagramSocket.java:301)
at communicate.text(communicate.java:21)
at communicate.main(communicate.java:10)
As "YO" is not printed it seems that error is in the text method where I am trying to create DatagramSocket. Where am I going wrong?
If you want read, do not bind the remote address. Just create a local UDP socket (it will be a server socket) and just read from/write to its buffer. You can bind to your local network interface only and these must be initialized before. So you cannot bind to an unused Wifi, or unplugged ethernet adapter.
If you want test a sender, and a receiver in the same java program on different threads, you have to use two different socket.
A hint: use InetAddress.getByName(IPv4) for string IP input, you do not need the byte array.
I'm trying to send a message using a udp client to udp server and send the message back to client with various metadata about the received message.
I have these two classes:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UdpDateClient {
public static void main(String[] args) throws IOException {
String host = "localhost";
if (args.length > 0)
host = args[0];
// get a datagram socket on any available port
try {
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = new byte[2048];
buf="hi it's Max".getBytes();
InetAddress address = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
buf = packet.getData();
int len = packet.getLength();
String received = (new String(buf)).substring(0, len);
System.out.println("From server: " + received);
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Date;
public class UdpDateServer {
private DatagramSocket socket = null;
private boolean moreClients = true;
public static void main(String[] args) {
UdpDateServer server = new UdpDateServer();
server.start();
}
public UdpDateServer() {
try {
socket = new DatagramSocket(4445);
System.out.println("server ready...");
} catch (SocketException e) {
e.printStackTrace();
System.exit(1);
}
}
public void start() {
DatagramPacket packet;
while (moreClients) {
try {
byte[] buf = new byte[2048];
// receive request
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("recieved packet from client: "+new String(packet.getData()));
// prepare response
String responseString = "Client's message received: "+new String(packet.getData())+"\n"
+ "Received on:" +new Date().toString();
buf = responseString.getBytes();
System.out.println("buf to be sent from server: "+(new String(buf)));
System.out.println("buf.length="+buf.length);
// send the response to "address" and "port"
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
moreClients = false;
}
}
socket.close();
}
}
what I get on the client side is only first 11 bytes of the message that is sent by the server:
Client side:
From server: Client's me
Server side:
server ready...
recieved packet from client: hi it's Max
buf to be sent from server: Client's message received: hi it's Max
Received on:Fri Aug 14 16:00:20 IDT 2015
buf.length=2116
As you can see, the message from server that is recieved back by the client is cut after 11 characters.
What am I doing wrong?
The problem is the line buf="hi it's Max".getBytes(); of the client code.
Here you set the buffer length to 11.
Your client code should look like the following
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = "hi it's Max".getBytes();
InetAddress address = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
// get response
buf = new byte[2048];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
buf = packet.getData();
int len = packet.getLength();
String received = (new String(buf)).substring(0, len);
System.out.println("From server: " + received);
socket.close();
byte[] buf = new byte[2048];
buf="hi it's Max".getBytes();
after this buf.length will be 11 not 2048!
And on your way back
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
will only receive 11 Bytes because buf.length is 11. Change the first block to something like
byte[] buf = new byte[2048];
System.arraycopy("hi it's Max".getBytes(), 0, buf, 0, 11);