I want to make my server able to accept messages from two clients. but something went wrong. Help needed! I tried to run same client twice, but received only one message and some errors.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Serv1 {
public static void main(String[] args) throws IOException {
Listner listner = new Listner();
Thread thread = new Thread(listner);
thread.start();
System.out.println("thread already started");
DatagramSocket s = new DatagramSocket(8787);
byte[] receiveData = new byte[1024];
System.out.println ("Waiting for datagram packet");
DatagramPacket p = new DatagramPacket(receiveData, receiveData.length);
System.out.println("about to receive packet N1");
s.receive(p);
String sentence = new String(p.getData());
InetAddress IPAddress = p.getAddress();
int port = p.getPort();
System.out.println ("From: " + IPAddress + ":" + port);
System.out.println ("Message: " + sentence);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
receiveData = new byte[1024];
System.out.println ("Waiting for datagram packet");
p = new DatagramPacket(receiveData, receiveData.length);
System.out.println("about to receive packet N2");
s.receive(p);
sentence = new String(p.getData());
IPAddress = p.getAddress();
port = p.getPort();
}
}
class Listner implements Runnable
{
public void run() {
String text = null;
while(true){
text = null;
int server_port = 8787;
byte[] receiveData = new byte[1024];
DatagramPacket p = new DatagramPacket(receiveData, receiveData.length);
DatagramSocket s = null;
try{
s = new DatagramSocket(server_port);
}catch (SocketException e) {
e.printStackTrace();
System.out.println("Socket excep, port used");
}
try {
s.receive(p);
}catch (IOException e) {
e.printStackTrace();
System.out.println("IO EXcept");
}
text = new String(receiveData, 0, p.getLength());
System.out.println("message = "+text);
s.close();
}
}
}
run:
thread already started
Waiting for datagram packet about to receive packet N1
java.net.BindException: Address already in use: Cannot bind at java.net.PlainDatagramSocketImpl.bind0(Native Method) at java.net.PlainDatagramSocketImpl.bind(PlainDatagramSocketImpl.java:91) at java.net.DatagramSocket.bind(Socket excep, port used DatagramSocket.java:372) at java.net.DatagramSocket.<init>(DatagramSocket.java:211) at java.net.DatagramSocket.<init>(DatagramSocket.java:262) at java.net.DatagramSocket.<init>(DatagramSocket.java:235) at serv1.Listner.run(Listner.java:29) at java.lang.Thread.run(Thread.java:662) Exception in thread "Thread-0" java.lang.NullPointerException at serv1.Listner.run(Listner.java:35) at java.lang.Thread.run(Thread.java:662) From: /192.168.1.102:58977 Message: hi, i am the first one Waiting for datagram packet about to receive packet N2 BUILD SUCCESSFUL (total time: 59 seconds)**strong text**