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();
}
}
...
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();
}
}
}
There are a few things that you might want to change here:
1) You are sending a UDP packet on port 4000 from your client but listening on port 3000 in your server(receiver) code. Ports should be same.
2) There might be another instance of your server code running in another Netbeans tab or from your terminal may be, which is already bound to the port. Please ensure that you have only one instance running for your server code. This will resolve your 'Address already in use error'
3) I also added 'Thread.sleep(500)' in the client(sender) code in the infinite while loop that you have set up. Without this, the code was ending up with a 'Bad File Descriptor' error on my machine. Probably it was a conflict with the Socket handle running into a problem with the infinite loop in place.
With these changes, data exchange between client and server is working fine.
Related
I want to send out a UDP packet/message out to another device on the same ethernet connection, but I'm not sure where a server/client relationship would be here.
The receiving message is configured to automatically send a response back upon receiving a message, so both devices would just be communicating to each other...
Am I missing something?
I'm confused because the code I used to send a message from a client to a server has parameters "server ip" and "server port" so I'm not sure if I can 1) just replace the parameters and use the same code and 2) if it's possible, what to put in those parameters, the initial device's port # and ip? Or the second device's?
Thanks!
The code snippet:
new Thread(new Runnable() {
#Override
public void run() {
try {
InetAddress SERVERIP = InetAddress.getByName(SERVER_IP);
DatagramSocket socket = new DatagramSocket();
socket.setBroadcast(true);
byte[] msg = message.getBytes();
DatagramPacket packet = new DatagramPacket(msg, message.length(),
SERVERIP, SERVERPORT);
socket.send(packet);
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}).start();
I'm not entirely sure if the question you want answered is how to respond to the device that sent the message from the device that received the message.
If this is the case then the following code is a basic example of how you could respond to the initial sender device by getting the address and port from the packet that was received over the socket.
// Receive and respond thread.
new Thread(new Runnable() {
#Override
public void run() {
try {
// Receive
DatagramSocket socket = new DatagramSocket(4445);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// Respond
// Get sender's/return address from the packet that was received.
InetAddress address = packet.getAddress();
// Get sender's/return port from the packet that was received.
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}).start();
I would also recommend reading the following documentation regarding writing a datagram server and client.
Am new to Socket programming am trying to establish a communication between a Server and a client but i don't know how to do that am a bit confused on how to go about it. I have written the program below but it is given error and i can't get my head round why.
package server;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Server {
public static void main(String[] args) {
// TODO code application logic here
try {
DatagramSocket socket = new DatagramSocket(7000);
socket.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
String message = new String (buffer);
System.out.println(message);
String Reply ="Am here";
DatagramPacket data = new DatagramPacket(Reply.getBytes(), Reply.getBytes().length, packet.getAddress(), packet.getPort());
socket.send(data);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
Client
package client;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main(String[] args) {
// TODO code application logic here
try{
String message = "Hello Server";
String host = "localhost";
InetAddress addr = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 7000);
DatagramSocket socket = new DatagramSocket(4000);
socket.send(packet);
DatagramSocket sockets = new DatagramSocket(7000);
sockets.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packets = new DatagramPacket(buffer,buffer.length);
sockets.receive(packets);
String messages = new String (buffer);
System.out.println(messages);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
How can i get them communicated. I have heard about Multi-threading but can't get my head round how it works.
I get the following error.
java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(DualStackPlainDatagramSocketImpl.java:84)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:93)
at java.net.DatagramSocket.bind(DatagramSocket.java:392)
at java.net.DatagramSocket.<init>(DatagramSocket.java:242)
at java.net.DatagramSocket.<init>(DatagramSocket.java:299)
at java.net.DatagramSocket.<init>(DatagramSocket.java:271)
at client.Client.main(Client.java:32)
If you wanting to send/receive from a client to a server using a socket then use ServerSocket on the serverside.
Then use accept - This listens for a connection to be made to this socket and accepts it.
The Socket object returned by Accept has Input and Output Stream which can be be read and written to.
The client will just use a Socket Object
See http://cs.lmu.edu/~ray/notes/javanetexamples/ for an example
If for some reason you insist on using DatagramSocket, then see this example https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
The error occurs because the port you are trying to bind your socket to is already in use. Port 7000 is used both by the client and server:
DatagramSocket sockets = new DatagramSocket(7000);
I'm working with a UDP Client (written in Java) and a Server (written in Lua). I'm using Lua Socket for the server and DatagramSockets for the client. Connection gets established successfully. The problem is when Lua server sends a string to the Java client, Java receive() function does not get the data and blocks. pls help me.
Lua server code:
-- Server
local socket = require("socket")
host = host or "*"
port = port or 8080
s = assert(socket.bind(host, port))
c = assert(s:accept())
data = "hello"
while true
do
assert(c:send(data .. "\n"))
socket.sleep(1)
-- return 0;
end
Java client code :
import java.net.*;
import java.io.*;
public class Clientnew
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = null;
byte[] Message = new byte[100];
try {
InetAddress IP = InetAddress.getLocalHost();
Socket client = new Socket(IP, 8080);
ds = new DatagramSocket(8080);
DatagramPacket dp = new DatagramPacket(Message, 1);
ds.receive(dp);
System.out.println("Recv\n");
String str = new String(dp.getData());
System.out.println(str);
} catch (Exception e)
{
} finally
{
if (ds != null)
{
ds.close();
}
}
}
}
Both program run on the Linux Platform.
Your Lua code is a TCP Server, not a UDP one. Also, remember that UDP is connectionless...
http://w3.impa.br/~diego/software/luasocket/udp.html
You can use standard tools like netstat to check things like this.
At work we are developing an android app that communicates with set top boxes(STB).
It all works fine but I'm trying to create a "mock" STB that the app can connect to so I can control the responses for testing.
I have no access to the code in the STB to know how they set up the sockets but I do have a simplified version of the client code used by the app.
Here's the client code:
public class UDPClient {
public static void main(String[] args) throws SocketException, UnknownHostException {
DatagramSocket c = new DatagramSocket(12345);
c.setBroadcast(true);
c.setSoTimeout(20000);
String msearchData = "DATA";
byte[] sendData = mSearchData.getBytes();
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
c.send(sendPacket);
System.out.println("Request packet sent");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// wait for reply
byte[] recBuf = new byte[15000];
DatagramPacket receivePacket = new DatagramPacket(recBuf, recBuf.length);
try {
c.receive(receivePacket);
System.out.println("PACKET RECEIVED!");
System.out.println(new String(receivePacket.getData()));
} catch (IOException e) {
e.printStackTrace();
}
c.close();
}
}
When I run this code on my development laptop (and I'm on a wireless network with that STB) the STB responds.
However, I have another laptop setup to pretend to be another STB on the same network(mock STB).
The "mock" STB simply refuses to pick up the broadcasts requests and I'm stuck.
Here's some code I use to act as the mock STB. I've tried various combinations of ports but nothing works.
public class MockBox {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
socket.setBroadcast(true);
while (true) {
System.out.println(">>>Ready to receive broadcast packets!");
byte[] recvBuf = new byte[15000];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(packet); // blocks
// Packet received
System.out.println(">>>Packet received from " + packet.getAddress().getHostAddress());
System.out.println(">>>Packet data: " + new String(packet.getData()));
socket.close();
}
}
}
Any help appreciated!
Disable the software firewall.
Use MulticastSocket instead of DatagramSocket. (Note: The address you specified above is a multicast address.)
Use TTL of at least 1. If that doesn't work, use 2. Repeat, but don't go above say 4 or 5 on a LAN, because at that point, you're already past reasonable. (Zero won't leave the machine. Using a value too high may cause the packet to be discarded somewhere along the route.)
On a single port I want to listen for Multicast, UDP, and TCP traffic. (on my LAN)
I also want to respond via UDP, if something is detected.
The code works below, but only for Multicast detection. The while(true) loop is definitely doing it just, from the main().
But I'm running into a wall with adding another protocol detection method.
Can a single application have multiple sockets open, in multiple protocols?
I'm sure it's my limited knowledge of threading, but maybe someone can see my hiccup below.
public class LANPortSniffer {
private static void autoSendResponse() throws IOException {
String sentenceToSend = "I've detected your traffic";
int PortNum = 1234;
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("192.168.1.121");
byte[] sendData = new byte[1024];
sendData = sentenceToSend.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, PortNum);
clientSocket.send(sendPacket);
clientSocket.close();
}//eof autoSendResponse
private static void MulticastListener() throws UnknownHostException {
final InetAddress group = InetAddress.getByName("224.0.0.0");
final int port = 1234;
try {
System.out.println("multi-cast listener is started......");
MulticastSocket socket = new MulticastSocket(port);
socket.setInterface(InetAddress.getLocalHost());
socket.joinGroup(group);
byte[] buffer = new byte[10*1024];
DatagramPacket data = new DatagramPacket(buffer, buffer.length);
while (true) {
socket.receive(data);
// auto-send response
autoSendResponse();
}
} catch (IOException e) {
System.out.println(e.toString());
}
}//eof MulticastListener
// this method is not even getting launched
private static void UDPListener() throws Exception {
DatagramSocket serverSocket = new DatagramSocket(1234);
byte[] receiveData = new byte[1024];
System.out.println("UDP listener is started......");
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("UDP RECEIVED: " + sentence);
}
}
public static void main(String[] args) throws Exception {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
try {
MulticastListener();
} catch (UnknownHostException e) {
e.printStackTrace();
}
// this does not appear to be detected:
try {
UDPListener();
} catch (Exception e) {
e.printStackTrace();
}
}
}//eof LANPortSniffer
In main(), I tried adding a second try/catch, for a simple UDPListener() method.
But it seems to be ignored when I run the application in Eclipse.
Does the main() method only allow for one try/catch?
In a nutshell, I'd like to listen on a single port for Multicast, UDP, and TCP packets all at the same time. Is this possible?
Your getting into a Threading issue here. I think you need to brush up on understanding of Java. When you call MulticastListener() it will never leave that block until your connection fails. It has a continous while loop. You need to create a new Thread for each of these activities.
Thread t = new Thread(new Runnable() {
public void run() {
MulticastListener();
}
}
t.start();
However I recommend you read up on your understanding of the programs flow and use of a more object orientated approach before you start trying to implement a threaded program.
1) You'll need raw socket access, which you won't get with a MulticastListener.
2) Look-up Promiscuous Mode and Raw Sockets in Java.
3) Threading issues are irrelevant - they will only give you better reactive performance - suggest you get it working with one thread before you improve your code.