UDP Broadcasting Issue - java

I was trying a simple problem of sending some random numbers from server to client by UDP Broadcasting. As far as I know, if I broadcast to a specific ip address and port number, all the users who are connected to that channel will be able to listen. I have looked for sample codes in the internet and developed my code based on that. But whenever I try to run the codes, my server closes the socket before client can get anything.
The server code is:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.security.SecureRandom;
public class Server {
public static void main(String[] args) throws IOException {
DatagramPacket packet;
InetAddress address;
DatagramSocket socket;
System.out.println("Sending Numbers!");
socket = new DatagramSocket();
try {
int n = 10;
SecureRandom rand = new SecureRandom();
address = InetAddress.getByName("233.0.0.1");
for(int i = 0; i < n; i++)
{
int num = rand.nextInt(100);
byte[] tmp = Integer.toString(num).getBytes();
packet = new DatagramPacket (tmp, 0, address, 1502);
socket.send(packet);
System.out.println("Number has been sent!");
}
} catch (Exception e) {
System.out.println("Error: " + e);
} finally {
try {
socket.close();
} catch (Exception e) {
System.out.println("Error2: " + e);
}
}
}
}
The client code is:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.ByteBuffer;
public class Client {
public static void main(String[] args) throws IOException {
// Initialization
int n = 10;
// Create the socket
int port = 1502;
DatagramSocket socket;
DatagramPacket packet = null;
socket = new DatagramSocket(port);
for (int i = 0; i < n; i++)
{
socket.receive (packet);
byte[] numb = packet.getData();
int num = ByteBuffer.wrap(numb).getInt();
System.out.println(Integer.toString(num));
}
}
}
Then, I tried to compile each code using javac and java.
javac Server.java
java package_name.Server
I am running the Server first using the above method, then Client. I get NullPointerException for client. It would be really helpful if I understand what am I doing wrong here.
I am running them in command window. For server, I get this
Server
And for Client: Client
Edit: I was able to communicate between Server and Client. However, I just keep getting the first number only. Moreover, if I initialize Datagram for size >2, I get NumberFormatException. This is the improved code.
Server Code:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.security.SecureRandom;
public class Server {
public static void main(String[] args) throws IOException {
DatagramPacket packet;
InetAddress address;
DatagramSocket socket;
System.out.println("Sending Numbers!");
socket = new DatagramSocket();
try {
int n = 10;
SecureRandom rand = new SecureRandom();
address = InetAddress.getByName("127.0.0.1");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream pout = new PrintStream( bout );
for(int i = 0; i < n; i++)
{
int num = rand.nextInt(100);
pout.print(num);
byte[] barray = bout.toByteArray();
packet = new DatagramPacket (barray, barray.length, address, 1502);
socket.send(packet);
System.out.println("Number has been sent!");
System.out.println(num);
}
} catch (Exception e) {
System.out.println("Error: " + e);
} finally {
try {
socket.close();
} catch (Exception e) {
System.out.println("Error2: " + e);
}
}
}
}
Client Code:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Client {
public static void main(String[] args) throws IOException {
// Initialization
int n = 10;
// Create the socket
int port = 1502;
DatagramSocket socket;
byte[] buf = new byte[2];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket = new DatagramSocket(port);
for (int i = 0; i < n; i++)
{
socket.receive (packet);
int num = Integer.parseInt(new String(packet.getData()));
System.out.println(num);
}
}
}
What can be the issue now?
Edit 2: Finally, I have made it work. Just put bout and pout inside the for loop and it should work!

you need to initialize your DatagramPacket in your client - it can not be null
int n = 10;
// Create the socket
int port = 1502;
DatagramSocket socket;
byte[] buf = new byte[1000];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket = new DatagramSocket(port);
for (int i = 0; i < n; i++)
{
socket.receive (packet);
byte[] numb = packet.getData();
int num = ByteBuffer.wrap(numb).getInt();
System.out.println(Integer.toString(num));
}
Also this code needs to be running before your Server

Related

I'm having trouble creating a simple Java UDP system

The sequence numbers aren't working as the int value seems to reset to 0 - or setting it again in the second method returns an error.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Client3.sendThenReceive(Client3.java:106)
at Client3.stopAndWait(Client3.java:69)
at Client3.main(Client3.java:41)
This is the client:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.nio.*;
public class Client3 {
private DatagramSocket datagramSocket;
private InetAddress inetAddress;
private byte [] buffer;
private int initialSequenceNumber = 100;
private int sequenceNumber;
private int testSN;
private static final int port = 1234;
private static final int BUFFER_SIZE = 1024;
private static final String HOSTNAME = "localhost";
private static String message;
public Client3(DatagramSocket datagramSocket, InetAddress inetAddress) {
this.datagramSocket = datagramSocket;
this.inetAddress = inetAddress;
}
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress inetAddress = InetAddress.getByName(HOSTNAME);
Client3 client = new Client3(datagramSocket, inetAddress);
System.out.println("Send datagram packets to a server");
Scanner scanner = new Scanner(System.in);
message = (scanner.nextLine() + " Umbrella");
scanner.close();
client.stopAndWait();
}
public void stopAndWait() throws IOException {
Client3 client = new Client3(datagramSocket, inetAddress);
sequenceNumber = initialSequenceNumber;
ByteArrayOutputStream test = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(test);
toSend.writeInt(sequenceNumber);
buffer = test.toByteArray();
DatagramPacket testConnection = new DatagramPacket(buffer, buffer.length, inetAddress, port);
System.out.println("testConnection sent, waiting for confirmation.");
datagramSocket.send(testConnection);
datagramSocket.receive(testConnection);
ByteArrayInputStream confirmConnection = new ByteArrayInputStream(testConnection.getData());
DataInputStream dis = new DataInputStream(confirmConnection);
int SN = dis.readInt();
//test code to show the received data to the console
//System.out.println(SN);
if (SN == sequenceNumber) {
System.out.println("Confirmation received. Proceeding to Message delivery.");
//testSN = sequenceNumber;
//System.out.println("test: " + testSN + " SN: " + sequenceNumber);
client.sendThenReceive();
}
else {
System.out.println("error - incorrect sequence number.");
}
}
public void sendThenReceive() {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
// Changing the variable here results in error and termination
//Is it because it is in the method?
//int newNumber = 101;
//testSN = 101;
//sequenceNumber = 101;
ByteArrayOutputStream test = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(test);
System.out.println("test: " + testSN + " SN: " + sequenceNumber);
toSend.writeInt(sequenceNumber);
toSend.writeUTF(message);
buffer = test.toByteArray();
System.out.println(message + " " + sequenceNumber);
DatagramPacket sentMessage = new DatagramPacket(buffer, buffer.length, inetAddress, port);
datagramSocket.send(sentMessage);
datagramSocket.receive(sentMessage);
ByteArrayInputStream test2 = new ByteArrayInputStream(sentMessage.getData());
DataInputStream dis = new DataInputStream(test2);
int SN = dis.readInt();
String messageFromServer = dis.readUTF();
if (SN == 101) {
System.out.println("The server says you said: " + messageFromServer);
sequenceNumber++;
Scanner newScanner = new Scanner(System.in);
message = (newScanner.nextLine() + " Umbrella");
newScanner.close();
}
else {
System.out.println("Error - incorrect sequence number.");
}
} catch (IOException e) {
e.printStackTrace();
break;
}
} scanner.close();
}
}
And this is the server:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.io.*;
import java.net.*;
import java.nio.*;
public class Server3 {
private DatagramSocket datagramSocket;
private byte[] dataForSend = new byte[256];
byte[] receiveData = new byte[ dataForSend_SIZE ];
//byte[] dataForSend = new byte[ dataForSend_SIZE ];
private int initialSequenceNumber = 100;
private int sequenceNumber;
private static final int port = 1234;
private static final int dataForSend_SIZE = 1024;
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(port);
Server3 server = new Server3(datagramSocket);
System.out.println("Server Operational");
server.testConnection();
}
public Server3(DatagramSocket datagramSocket) {
this.datagramSocket = datagramSocket;
}
public void testConnection() throws IOException {
while (true) {
try {
sequenceNumber = initialSequenceNumber;
DatagramPacket receivedMessage = new DatagramPacket (receiveData, receiveData.length);
datagramSocket.receive(receivedMessage);
InetAddress inetAddress = receivedMessage.getAddress();
int port = receivedMessage.getPort();
ByteArrayInputStream test = new ByteArrayInputStream(receivedMessage.getData());
DataInputStream dis = new DataInputStream(test);
int a10 = dis.readInt();
System.out.println("SN read from Datagram: " + a10);
if ( a10 == sequenceNumber) {
System.out.println("Connection Test Successfully Received.");
ByteArrayOutputStream confirmConnection = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(confirmConnection);
toSend.writeInt(sequenceNumber);
dataForSend = confirmConnection.toByteArray();
DatagramPacket testConnection = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
datagramSocket.send(testConnection);
System.out.println("'confirmConnection' has been sent.");
sequenceNumber++;
receiveThenSend();
}
else {
System.out.println("error - incorrect sequence number."); }
}
finally {
}
}
}
public void receiveThenSend() throws IOException {
while (true) {
try {
sequenceNumber = 101;
DatagramPacket sentMessage = new DatagramPacket(receiveData, receiveData.length);
datagramSocket.receive(sentMessage);
InetAddress inetAddress = sentMessage.getAddress();
int port = sentMessage.getPort();
ByteArrayInputStream test = new ByteArrayInputStream(sentMessage.getData());
DataInputStream dis = new DataInputStream(test);
int SN = dis.readInt();
System.out.println("SN received: " + SN);
System.out.println("SN on File: " + sequenceNumber);
String messageFromClient = dis.readUTF();
if (SN == sequenceNumber) {
//String messageFromClient = new String(sentMessage.getData(), 0, sentMessage.getLength());
System.out.println("SN: Match.");
System.out.println("Message from Client: " + messageFromClient);
System.out.println("Response sent.");
ByteArrayOutputStream serverResponse = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(serverResponse);
toSend.writeInt(101);
toSend.writeUTF(messageFromClient);
dataForSend = serverResponse.toByteArray();
sentMessage = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
datagramSocket.send(sentMessage);
}
else {
System.out.println("Error - incorrect sequence number.");
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}
Can anyone see why these would be resetting, please?
The Exception you're getting is caused by closing the Scanner. When a Scanner instance is closed, it closes the underlying stream which is System.in in your case.
So next time when you create the Scanner, it's created over a closed stream and .nextLine() throws the exception you're seeing.
Here's a snippet that reproduces the issue:
Scanner s1 = new Scanner(System.in);
s1.close();
Scanner s2 = new Scanner(System.in);
s2.nextLine(); //Exception in thread "main" java.util.NoSuchElementException: No line found

Java Datagram Packet buffer printing extra white spaces and newlines

I am learning Java networking and am trying to implement a simple UDP server-client program which exchanges messages between server and client. The program is working, but when I print the buffer, a lot of newlines get printed. What am I doing wrong? Here is my code for the server:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.net.SocketException;
class Q1Server {
private DatagramSocket ds;
private byte[] buff1, buff2;
private DatagramPacket dp1 = null, dp2 = null;
private InetAddress clientIP;
private int clientPort;
public Q1Server() throws SocketException{
ds = new DatagramSocket(1234);
buff1 = new byte[10000];
buff2 = null;
while(true) {
try {
dp1 = new DatagramPacket(buff1, buff1.length);
System.out.println("Waiting for connection...");
ds.receive(dp1);
System.out.print(new String(buff1, "UTF-8"));
buff1 = new byte[10000];
clientIP = dp1.getAddress();
clientPort = dp1.getPort();
System.out.println("Connected to IP: " + clientIP + " Port: " + clientPort);
buff2 = ("Thanks for connecting to the server!!!").getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, clientIP, clientPort);
ds.send(dp2);
String cl = "";
while (!cl.equals("close")) {
dp1 = new DatagramPacket(buff1, buff1.length);
ds.receive(dp1);
System.out.println("here");
cl = new String(buff1, "UTF-8");
buff1 = new byte[10000];
System.out.println("Client: " + cl);
}
buff2 = ("Closing...\nGoodbye!!!").getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, clientIP, clientPort);
ds.send(dp2);
} catch(IOException i) {
i.printStackTrace();
}
}
}
public static void main(String[] args) throws SocketException {
Q1Server server = new Q1Server();
}
}
And here is the code for client:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
class Q1Client {
private DatagramSocket ds;
private Scanner scanner;
private InetAddress ip;
private byte[] buff1, buff2;
private DatagramPacket dp1 = null, dp2 = null;
public Q1Client() throws SocketException, UnknownHostException {
ds = new DatagramSocket();
ip = InetAddress.getLocalHost();
buff1 = new byte[10000];
buff2 = null;
scanner = new Scanner(System.in);
try {
buff2 = ("Start").getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, ip, 1234);
ds.send(dp2);
dp1 = new DatagramPacket(buff1, buff1.length);
ds.receive(dp1);
System.out.println(new String(buff1, "UTF-8"));
buff1 = new byte[10000];
String msg = "";
while(!msg.equals("close")) {
System.out.println("here");
msg = scanner.nextLine();
System.out.println("Typed: " + msg);
buff2 = msg.getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, ip, 1234);
ds.send(dp2);
}
dp1 = new DatagramPacket(buff1, buff1.length);
ds.receive(dp1);
System.out.println(new String(buff1, "UTF-8"));
} catch(IOException i) {
i.printStackTrace();
}
}
public static void main(String[] args) throws SocketException, UnknownHostException{
Q1Client client = new Q1Client();
}
}
I think the problem may be due to the size of the buffer. The byte buffer array is pre-initialized with the size that large than the actual text being sent. But what is the other way to do it? How do I know the size of the buffer dynamically?

Many clients using different computers java chatbox

I am making a simple java chatbox using sockets. When I run many clients on same computer, everything's alright, but when I try it on different PCs, they don't share the information. How could I fix that? I guess that has something to do with port and host, not sure though. My connecting method is below.
public static void Connect() {
try {
final int port = 444;
String hostname = "";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
final String host = "Laurie-PC";
Socket sock = new Socket(host, port);
System.out.println("You connected to " + host);
ChatClient = new A_Chat_Client(sock);
PrintWriter out = new PrintWriter(sock.getOutputStream());
out.println(UserName);
out.flush();
Thread X = new Thread(ChatClient);
X.start();
} catch (Exception E) {
System.out.println(E);
JOptionPane.showMessageDialog(null, "Server not responding");
System.exit(0);
}
}
this is the server code
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class A_Chat_Server {
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
public static void main(String[] args) throws IOException {
try {
final int port = 444;
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for clients...");
A_Chat_Client_GUI.main(args);
while (true) {
Socket sock = server.accept();
ConnectionArray.add(sock);
System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
AddUserName(sock);
A_Chat_Server_Return chat = new A_Chat_Server_Return(sock);
Thread X = new Thread(chat);
X.start();
}
} catch (Exception X) {
System.out.println(X);
}
}
public static void AddUserName(Socket X) throws IOException {
Scanner input = new Scanner(X.getInputStream());
String UserName = input.nextLine();
CurrentUsers.add(UserName);
for (int i = 0; i < A_Chat_Server.ConnectionArray.size(); i++) {
Socket temp_sock = A_Chat_Server.ConnectionArray.get(i);
PrintWriter out = new PrintWriter(temp_sock.getOutputStream());
out.println("????1!!!!!!???#######22" + CurrentUsers);
out.flush();
}
}
}

How to find online users in a local area peer to peer network?

I am currently working on a small peer to peer application in which users can chat with each other within a LAN. I have currently implemented the following code to broadcast by a user that s/he is online.
import java.io.*;
import java.net.*;
class BroadcastOnline extends Thread{
public void run(){
try{
String string = "a";
DatagramSocket serverSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("255.255.255.255");
byte[] sendData = new byte[1];
sendData = string.getBytes();
for(;;){
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9877);
serverSocket.send(sendPacket);
Thread.sleep(1000);
}
} catch (Exception e){}
}
}
And I have used following code to find who are online.
import java.io.*;
import java.net.*;
class FindUsers {
InetAddress ad;
String ipaddress;
String onlineUsers[] = new String [10];
FindUsers() throws Exception{
DatagramSocket clientSocket = new DatagramSocket(9877);
int count=0;
byte[] receiveData = new byte[1];
for(int i=0;i<=9;i++){
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
ad = receivePacket.getAddress();
ipaddress = ad.getHostAddress();
onlineUsers[i]=ipaddress;
count++;
}
}
}
But the problem is that the above codes are running in infinite loop. And I think the implementation is a bit silly.
Are there any other ways to implement this feature?
EDIT:
I got the solution to list IP addresses in the list.
How can I get and keep the user friendly names in the list?
You need to broadcast the name like following in the BroadcastOnline class:
byte[] sendData = new byte[15];
String name = nameField.getText();
sendData = name.getBytes();
for(;;){
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9877);
serverSocket.send(sendPacket);
Thread.sleep(1000);
}
**of course it is needed to catch exception above
And to find users who are online, implement the following code.
import java.io.*;
import java.net.*;
import java.util.List;
import java.util.ArrayList;
public class FindUsers{
InetAddress inetAddress;
List<String> ipList = new ArrayList<String>();
List<String> nameList = new ArrayList<String>();
String ipAddress;
String name;
DatagramSocket clientSocket;
DatagramPacket receivePacket;
int count=0;
byte[] receiveData;
long futureTime;
Thread collect;
boolean refresh = true;
public FindUsers(){
futureTime = System.currentTimeMillis()+1100;
try{
clientSocket = new DatagramSocket(9877);
}
catch(IOException e){
e.printStackTrace();
System.out.println(e.toString());
}
collect = new Thread(new Runnable(){
public void run(){
for(;;){
receiveData = new byte[15];
receivePacket = new DatagramPacket(receiveData, receiveData.length);
try{
clientSocket.receive(receivePacket);
inetAddress = receivePacket.getAddress();
ipAddress = inetAddress.getHostAddress();
}
catch(IOException e){
//e.printStackTrace();
}
if(!ipList.contains(ipAddress)){
name = new String( receivePacket.getData());
ipList.add(ipAddress);
nameList.add(name);
receiveData = null;
}
try{
Thread.sleep(10);
}
catch(InterruptedException e){
//System.out.println("\nInterrupted!");
return;
}
}
}
});
collect.start();
while(System.currentTimeMillis()<=futureTime){
//do nothing.
}
clientSocket.close();
collect.interrupt();
int size = nameList.size();
if (size==0){
System.out.println("No online servers.");
}
else{
for(int i = 0; i< nameList.size();i++){
System.out.println(nameList.get(i)+ ": "+ ipList.get(i));
}
}
}
public static void main(String[] args){
FindUsers f = new FindUsers();
}
}
Hope this will help.

Multi-threaded UDP chat application in Java giving java.net.SocketException: Socket closed

I am trying to implement a chat application in Java using UDP for multiple clients. I used thread to accept input on server side and another thread to handle the input as well. My code is:
Server side:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
public class ChatServer
{
static DatagramSocket socket;
static DatagramPacket packet;
static ArrayList<InetAddress> arrayList;
static LinkedBlockingQueue<byte[]> messages;
public static void main(String[] args) throws IOException
{
arrayList = new ArrayList<InetAddress>();
messages = new LinkedBlockingQueue<byte[]>();
byte[] b = new byte[500];
System.out.println("Server initialized..");
socket = new DatagramSocket(Integer.parseInt(args[0]));
packet = new DatagramPacket(b, b.length);
Thread acceptorThread = new Thread()
{
public void run()
{
while(true)
{
try
{
socket.receive(packet);
System.out.println("acceptor");
if(arrayList.add(packet.getAddress()))
System.out.println("listtrue");
if(messages.add(packet.getData()))
System.out.println("queuetrue");;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
acceptorThread.start();
Thread messageHandler = new Thread()
{
public void run()
{
System.out.println("handler");
while(true)
{
if(messages.poll() != null)
{
byte []b = "soham".getBytes();
sendAll(b);
}
}
}
};
messageHandler.start();
}
public static void sendAll(byte[] b)
{
for(InetAddress address : arrayList)
{
DatagramPacket packet = new DatagramPacket(b, b.length, address, 4445);
try
{
socket.send(packet);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
socket.close();
}
}
}
}
and the client side is :
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class ChatClient {
public static void main(String[] args) throws IOException
{
while(true)
{
//get input
System.out.println("Message:");
Scanner sc = new Scanner(System.in);
String message = sc.next();
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = new byte[256];
buf = message.getBytes();
InetAddress address = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, Integer.parseInt(args[0]));
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println(packet.getSocketAddress()+" " + received);
}
}
}
stacktrace after execution gives me :
java.net.SocketException: Socket closed
at java.net.DualStackPlainDatagramSocketImpl.checkAndReturnNativeFD(Unknown Source)
at java.net.DualStackPlainDatagramSocketImpl.receive0(Unknown Source)
at java.net.AbstractPlainDatagramSocketImpl.receive(Unknown Source)
at java.net.DatagramSocket.receive(Unknown Source)
at snippet.ChatServer$1.run(ChatServer.java:40)
I cannot identify the problem. Any help would be appreciated, cheers.
Your sendAll method is closing the socket after every (the first) sent packet.
You have misunderstood the meaning of the finally block. It is currently executed in each iteration of sendAll. You are closing the socket for every client when you should be doing it only for the last one.

Categories

Resources