I have a problem to run a server and clients in one (mac) machine. I can run the server but when I run the client it give me an error java.net.BindException: Address already in use
at java.net.PlainDatagramSocketImpl.bind0(Native Method)
as far as I know that there is somthing call ssh that need to be used but I don't know how to use it to do solve this.
Thanks
public class WRRCourseWork {
public static void main(String[] args) {
try {
DatagramSocket IN_socket = new DatagramSocket(3000);
DatagramSocket OUT_socket = new DatagramSocket(5000);
IN_socket.setSoTimeout(0);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
//recive the message
IN_socket.receive(packet);
String message = new String(buffer);
System.out.println("Got message: " + message.trim());
// send the message
String host = "";
InetAddress addr = InetAddress.getByName(host);
DatagramPacket OUT_Packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 5000);
OUT_socket.send(OUT_Packet);
System.out.println("Sending Message: "+ message.trim());
}
} catch (Exception error) {
error.printStackTrace();
}
}
... client
public class Messages {
public static void main(String [] args) {
System.out.println("hiiiiiii");
//String host = "localhost";
try {
while (true) {
InetAddress addr = InetAddress.getLocalHost();
String message = "Hello World";
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 4000);
DatagramSocket socket = new DatagramSocket(4000);
socket.send(packet);
//socket.close();
}
} catch(Exception error) {
// catch all errors
error.printStackTrace();
}
}
}
Your server is listening on port 3000 so change your client to also use port 3000 and to only specify port 3000 once, in the packet definition not in the socket.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Messages {
public static void main(String [] args) {
System.out.println("hiiiiiii");
//String host = "localhost";
DatagramSocket socket = null;
try {
while (true) {
InetAddress addr = InetAddress.getLocalHost();
String message = "Hello World";
DatagramPacket packet =
new DatagramPacket(message.getBytes(),
message.getBytes().length, addr, 3000);
socket = new DatagramSocket();
socket.send(packet);
socket.close();
}
} catch(Exception error) {
// catch all errors
error.printStackTrace();
}
}
}
The results on the server should then be:
Got message: Hello World
Sending Message: Hello World
Got message: Hello World
Sending Message: Hello World
Got message: Hello World
Sending Message: Hello World
. . .
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 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);
}
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.
For my class project I have the following problem. I am able to receive client information and re-send the info to the respective client. However, I am not being able to send every clients' info to every other client (Broadcast?). I also need to implement the given functions. Any help would be appreciated.
The goal is to design and implement a simple application layer protocol over UDP to
facilitate High Availability Cluster (HAC). HAC has a set of mechanism to detect failovers,
network/node failure etc. in order to re-route the traffic to the available systems. In this project
you will not be working on the questions like how to perform consistent failover, or high
availability distributed hypervisor. However, your task is to design and implement a protocol to
maintain the up-node information throughout the cluster.
Your designed protocol should perform the following functions:
a) To detect node failure periodically
b) To inform the other nodes in the network about the failure (peering option)
c) To be able to detect when the failed node comes back to life
d) To inform other nodes about the availability of new node
Client Class:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.util.Random;
public class UDPClient
{
DatagramSocket Socket;
public UDPClient()
{
}
public void createAndListenSocket() throws ClassNotFoundException, InterruptedException
{
try
{
Socket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] incomingData = new byte[1024];
String sentence = "Client 1 is up";
byte[] data = sentence.getBytes();
boolean flag = true;
CreatePacket packet = new CreatePacket(data, flag, data.length);
while(true)
{
//Serialize to send
Random rnd = new Random();
int timeout = rnd.nextInt(30);
Thread.sleep(timeout*1000);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(buffer);
out.writeObject(packet);
out.close();
buffer.close();
DatagramPacket sendPacket = new DatagramPacket(buffer.toByteArray(), buffer.size(), IPAddress, 9876);
Socket.send(sendPacket);
System.out.println("Message sent from client");
//Deserialize and receive packet from server
DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
Socket.receive(incomingPacket);
ByteArrayInputStream bis = new ByteArrayInputStream(incomingPacket.getData());
ObjectInputStream in = new ObjectInputStream(bis);
Object receivedPacket = in.readObject();
in.close();
InetAddress IPAddress1 = incomingPacket.getAddress();
int port = incomingPacket.getPort();
System.out.println();
System.out.println("Response from server: ");
System.out.println("Message : " + receivedPacket.toString());
System.out.println("Client IP: "+ IPAddress1.getHostAddress());
System.out.println("Client port: "+ port);
}
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
UDPClient client = new UDPClient();
client.createAndListenSocket();
}
}
Server code:
public class UDPServer
{
DatagramSocket socket = null;
public UDPServer()
{
}
public void createAndListenSocket() throws ClassNotFoundException
{
try
{
socket = new DatagramSocket(9876);
byte[] incomingData = new byte[1024];
while (true)
{
DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
socket.receive(incomingPacket);
CreatePacket toSendPacket = new CreatePacket(incomingData, incomingData.length);
ArrayList <CreatePacket> clients = new ArrayList<CreatePacket>(4);
ByteArrayInputStream bis = new ByteArrayInputStream(incomingPacket.getData());
ObjectInputStream in = new ObjectInputStream(bis);
Object receivedPacket = in.readObject();
in.close();
clients.add(toSendPacket);
InetAddress IPAddress = incomingPacket.getAddress();
int port = incomingPacket.getPort();
System.out.println();
System.out.println("" + receivedPacket.toString());
System.out.println("Client IP: "+ IPAddress.getHostAddress());
System.out.println("Client port: "+ port);
DatagramPacket replyPacket = new DatagramPacket(incomingData, incomingData.length, IPAddress, port);
Thread.sleep(10*1000);
socket.send(replyPacket);
//socket.close();
}
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (IOException i)
{
i.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException, IOException
{
UDPServer server = new UDPServer();
server.createAndListenSocket();
}
}
You want
1 - client to send message to server if it is up/alive
2 - and for server to send some message to all client if it receives signal right?
I am not sure but you can try this,
InetAddress IPAddress = incomingPacket.getAddress();
int port = incomingPacket.getPort();
as you are getting IP address of one client you can store address of all clients on server side which are up/alive in a List or array. Then if you receives signal to server use that list to send respond.
You will need to update list according to up/alive clients.
I have a server and a client(say client1) both on a single file working perfectly. I have a situation like: I have another client(say client2) which sends information to the server. This server has to send the information taken from client2 to client1. But when I used same port number and same IP Address on both the server and client1 when I try to send information from client2, the client1 is also accepting at a time.
How can I send the information from client2 so that first server first accepts it and then sends that information to client1?
Client2 Code:
import java.io.*;
import java.net.*;
class Client1
{
public static void main(String[] args)throws Exception {
try {
InetAddress ip=InetAddress.getByName("228.5.6.7");
int port=4270;
MulticastSocket sock=new MulticastSocket();
String msg="Hello All";
DatagramPacket packet;
while(true)
{
packet =new DatagramPacket(msg.getBytes(),msg.length(),ip,port);
sock.send(packet);
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My Server and Client Code:
class Server implements Runnable
{
public void run()
{
try
{
//get the multicast ip
InetAddress ip = InetAddress.getByName("228.5.6.7");
int port=4270;
byte[] buffer=new byte[100];
byte[] data = null;
MulticastSocket sock=new MulticastSocket(port);
//join the multicast group
sock.joinGroup(ip);
while(true)
{
//create a datagram packet in which u will receive the msg
Thread.sleep(2000);
DatagramPacket pack=new DatagramPacket(buffer,buffer.length);
sock.receive(pack);
String msg = new String(buffer);
System.out.println("Sever Has Received :" +msg);
//SENDING THE MESSAGE TO CLIENT
System.out.println("Sending the Message!!!");
data = msg.getBytes();
DatagramPacket pack1 = new DatagramPacket(data,msg.length(),ip,port);
Thread.sleep(2000);
sock.send(pack1);
}
}
catch (Exception ex) {
Thread t = Thread.currentThread();
t.getUncaughtExceptionHandler().uncaughtException(t, ex);
}
}
}
Client1 Code:
class Client implements Runnable
{
public void run()
{
try {
InetAddress address1 = InetAddress.getByName("228.5.6.7");
int port=4271;
MulticastSocket socket1 = new MulticastSocket(port);
//join a Multicast group and send the group salutations
socket1.joinGroup(address1);
byte[] data1 = new byte[256];
DatagramPacket packet1 = new DatagramPacket(data1,data1.length);
while(true)
{
// receive the packets
socket1.receive(packet1);
String str = new String(packet1.getData(),0,packet1.getLength());
Thread.sleep(2000);
System.out.println("Client Received : "+str);
}
}
catch (Exception ex) {
Thread t = Thread.currentThread();
t.getUncaughtExceptionHandler().uncaughtException(t, ex);
}
}
}
MAIN PROGRAM
class ClientAndServer
{
public static void main(String[] args)
{
Server s = new Server();
//First start Server and then Start client
Thread t1 = new Thread(s);
t1.start();
Client c = new Client();
Thread t2 = new Thread(c);
t2.start();
}
}
Since you are using a MulticastSocket to link Client1 <-> Server <-> Client2. If Server send a message, EVERY client will received it, this is from the MulticastSocket doc
When one sends a message to a multicast group, all subscribing recipients to that host and port receive the message
If you don't want that, you might need to use two distinct socket, using two port
port 1 : Client1 <-> Server
port 2 : Client2 <-> Server
And you can then redirect the message only to one or the other port but will have two distinct channel of message