Java UDP server - java

I am new to Java programming and I am trying to create a UDP server. When I compile the code it says it could not listen to port 4722 and I would like to know why. Below is the code. I would be grateful for any advice.
import java.net.*;
import java.io.*;
public class Server
{
public static void main(String[] args) throws IOException
{
DatagramSocket serverSocket = new DatagramSocket(4722);
Socket clientSocket = null;
byte[] receiveData = new byte[1024];
byte[] sendData = new byte [1024];
boolean command = true;
try
{
serverSocket = new DatagramSocket(4722);
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
System.out.println("Waiting for client...");
}
catch (IOException e)
{
System.err.println("Could not listen on port: 4722.");
System.exit(1);
}
DatagramPacket packet = new DatagramPacket (sendData,sendData.length,4722);
serverSocket.send(packet);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
mathematicalProtocol bbm = new mathematicalProtocol();
outputLine = bbm.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null)
{
if(inputLine.equals("Bye."))
break;
outputLine = bbm.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}

You are initializing serverSocket and then making a new DatagramSocket on the same port again (and you can't do that as it's already bound on the first DatagramSocket). I.e. remove the following line:
serverSocket = new DatagramSocket(4722);

Here is a complete example of client/server UDP communication.
The server read data from a file and send each line to the client.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* #author nono
*
*/
public class UDPFileSender {
static class Client implements Runnable {
// Reception socket
private DatagramSocket socket;
// UDP packet to receive data into
private DatagramPacket packet;
// Flag for initialisation
private boolean failedInit = true;
/**
* Client constructor.
* #param receptionPort
* #param packetMaxLenght
*/
public Client(int receptionPort, int packetMaxLenght) {
try {
// Create the socket using the reception port
this.socket = new DatagramSocket(receptionPort);
// Init the packet
this.packet = new DatagramPacket(new byte[packetMaxLenght],packetMaxLenght);
this.failedInit = false;
} catch (SocketException e) {
//Port already used or other error
e.printStackTrace();
}
}
#Override
public void run() {
if(failedInit){
return;
}
// Loop undefinitly
while(true){
try {
System.out.println("Waiting for packet...");
// Wait for packet
socket.receive(packet);
// Assuming you are receiving string
String msg = new String(packet.getData());
System.out.println("Received : " + msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
int port = 4722;
//Start a client that can listen
new Thread(new Client(port,1024)).start();
// Creaete a reader
BufferedReader reader = new BufferedReader(new FileReader("File.txt"));
//Create a socket
DatagramSocket socket = new DatagramSocket();
// Create a packet
byte[] data = new byte[1024]; // Max length
DatagramPacket packet = new DatagramPacket(data, data.length);
// Set the destination host and port
packet.setAddress(InetAddress.getByName("localhost"));
packet.setPort(port);
String line = null;
while((line = reader.readLine()) != null){
//Set the data
packet.setData(line.getBytes());
//Send the packet using the socket
System.out.println("Sending : " + line);
socket.send(packet);
Thread.sleep(200);
}
//Close socket and file
reader.close();
socket.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
If your file contains :
Hello
World
You should see :
Waiting for packet...
Sending : Hello
Received : HelloWaiting for packet...
Sending : World
Received : World
Waiting for packet...

Related

How to send arralist on client by multithread server?

I want to send arraylist on multithreading server to client . So far i just write the conection and the clients can write and send to server msg ,the server just send back the msg to client is write somathing just sending. My main problems is how to transfer from server to client the arraylist ?
i am new on this and i dont know nothing for arralist .
code server :
import java.io.*;
import java.net.*;
import java.util.ArrayList;
// Server class
class Server {
public static void main(String[] args)
{
private ArrayList<Objects> Obj = new ArrayList<Objects>();
// file read
// String filePath = "Hotels_new.txt";
// System.out.println(Read_File( filePath ));
ServerSocket server = null;
try {
// server is listening on port 1234
server = new ServerSocket(1234);
server.setReuseAddress(true);
// running infinite loop for getting
// client request
while (true) {
// socket object to receive incoming client
// requests
Socket client = server.accept();
// Displaying that new client is connected
// to server
System.out.println("New client connected" + client.getInetAddress().getHostAddress());
// create a new thread object
ClientHandler clientSock = new ClientHandler(client);
// This thread will handle the client
// separately
new Thread(clientSock).start();
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (server != null) {
try {
server.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static String Read_File(String filePath)
{
// Declaring object of StringBuilder class
StringBuilder builder = new StringBuilder();
// try block to check for exceptions where
// object of BufferedReader class us created
// to read filepath
try (BufferedReader buffer = new BufferedReader(
new FileReader(filePath))) {
String str;
// Condition check via buffer.readLine() method
// holding true upto that the while loop runs
while ((str = buffer.readLine()) != null) {
builder.append(str).append("\n");
}
}
// Catch block to handle the exceptions
catch (IOException e) {
// Print the line number here exception occurred
// using printStackTrace() method
e.printStackTrace();
}
// Returning a string
return builder.toString();
}
// ClientHandler class
private static class ClientHandler implements Runnable {
private final Socket clientSocket;
// Constructor
public ClientHandler(Socket socket)
{
this.clientSocket = socket;
}
public void run()
{
PrintWriter out = null;
BufferedReader in = null;
try {
// get the outputstream of client
out = new PrintWriter( clientSocket.getOutputStream(), true);
// get the inputstream of client
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
// writing the received message from
// client
System.out.printf(" Sent from the client: %s\n",line);
out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null)
{
in.close();
clientSocket.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
code client:
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.ArrayList;
// Client class
class Client {
// driver code
public static void main(String[] args)
{
// establish a connection by providing host and port
// number
try (Socket socket = new Socket("localhost", 1234)) {
// writing to server
PrintWriter out = new PrintWriter(
socket.getOutputStream(), true);
// reading from server
BufferedReader in
= new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// object of scanner class
Scanner sc = new Scanner(System.in);
String line = null;
while (!"exit".equalsIgnoreCase(line)) {
// reading from user
line = sc.nextLine();
// sending the user input to server
out.println(line);
out.flush();
// displaying server reply
System.out.println("Server replied "
+ in.readLine());
}
// closing the scanner object
sc.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
In order to send something more complex you will have to serialize it. You can choose how to do the serialization, maybe the easiest is to use ObjectOutputStream and ObjectInputStream on the server and client respectively. These can be used very similarly to the PrintWriter / BufferedReader solution you are doing now.
I had to change a few things as your example code did not compile.
Example server based on your code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
public class Server {
private static final List<Integer> myIntArray = List.of(1, 2, 3);
public static void main(String[] args) {
ServerSocket server = null;
try {
// server is listening on port 1234
server = new ServerSocket(1234);
server.setReuseAddress(true);
// running infinite loop for getting
// client request
while (true) {
// socket object to receive incoming client
// requests
Socket client = server.accept();
// Displaying that new client is connected
// to server
System.out.println("New client connected" + client.getInetAddress().getHostAddress());
// create a new thread object
ClientHandler clientSock = new ClientHandler(client);
// This thread will handle the client
// separately
new Thread(clientSock).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// ClientHandler class
private static class ClientHandler implements Runnable {
private final Socket clientSocket;
// Constructor
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
while (in.readLine() != null) {
objectOutputStream.writeObject(myIntArray);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Example client:
import java.io.*;
import java.net.*;
import java.util.*;
// Client class
class Client {
// driver code
public static void main(String[] args) {
// establish a connection by providing host and port
// number
try (Socket socket = new Socket("localhost", 1234);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
// object of scanner class
Scanner sc = new Scanner(System.in);
String line = null;
while (!"exit".equalsIgnoreCase(line)) {
// reading from user
line = sc.nextLine();
// sending the user input to server
out.println(line);
out.flush();
// displaying server reply
List<Integer> integers = (List<Integer>) ois.readObject();
System.out.println("server: " + integers.get(0));
}
// closing the scanner object
sc.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Keep in mind that if you are about to send your own custom types, both sides will have to know about those to be able to serialize/deserialize. Also, your classes will have to be serializable.

Java socket write issues

I am trying to create a Modbus setup as follows:
client <----> IED <----> Modbus Server
IED has the IP 192.168.x.x and Modbus Server uses localhost as IP. All entities are in the same VM. The client is supposed to send a request to the IED,the IED forwards it to the server and the server responds to the IED.
The problem is the IED receives the request from the master which is stored in a byte array but transmitting the request to the server does not work. Wireshark traces show that the TCP connection is established with the server but request is not transmitted.
See the code below:
public class App {
public static void main(String[] args) {
IEDServer iedServer = new IEDServer();
iedServer.start(502);
}
}
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
public class IEDServer {
private ServerSocket serverSocket;
public void start (int port){
try {
InetAddress inetAddress = InetAddress.getByName("192.168.20.138");
serverSocket = new ServerSocket(port, 1024, inetAddress);
while (true){
new ClientHandler(serverSocket.accept()).start();
System.out.println("Connection accepted");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop(){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.Socket;
public class ClientHandler extends Thread{
private Socket clientSocket;
private DataOutputStream out;
private DataInputStream in;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
//connection from client
out = new DataOutputStream (clientSocket.getOutputStream());
in = new DataInputStream(clientSocket.getInputStream());
// in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// String readline;
//for connection to modbus server
Socket modbusSocket = new Socket("127.0.0.1",502);
modbusSocket.setSoTimeout(10000);
DataOutputStream modbus_out = new DataOutputStream (clientSocket.getOutputStream());
DataInputStream modbus_in = new DataInputStream(clientSocket.getInputStream());
byte [] modbus_bytes = {};
//read Modbus bytes from client to get client request
modbus_bytes = in.readAllBytes();
System.out.println("Modbus request: ");
for (byte b: modbus_bytes){
System.out.print(b);
}
System.out.println();
//transfer modbus request to modbus server
modbus_out.write(modbus_bytes, 0, modbus_bytes.length);
//get response from modbus server
modbus_bytes = modbus_in.readAllBytes();
System.out.println("Modbus response: ");
for (byte b: modbus_bytes){
System.out.print(b);
}
System.out.println();
//transfer response to client
out.write(modbus_bytes,0,modbus_bytes.length);
} catch (IOException e) {
e.printStackTrace();
}
//close TCP connection
try {
in.close();
out.close();
clientSocket.close();
System.out.println("Connection terminated");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Connection termination failed");
}
}
}
Also find below, the wireshark screenshot
Call DataOutputStream.flush() after DataOutputStream.write() to force the bytes to be send
I managed to fix it. I mistakenly passed clientSocketinstead of modbusSocketas a parameter to the modbus_inand modbus_outStream instances. I also had to poll for availability of data before reading and then writing. Also, I noticed that the client-side closed the TCP session while the server-side had it open. So I ensured that the connection was closed after each query.
Please find modified code below for ClientHandler:
import java.io.*;
import java.net.Socket;
public class ClientHandler extends Thread {
private Socket clientSocket;
private Socket modbusSocket;
private DataOutputStream out, modbus_out;
private DataInputStream in, modbus_in;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
System.out.println(clientSocket.getInetAddress());
try {
out = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
// in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// String readline;
//for connection to modbus server
modbusSocket = new Socket("127.0.0.1", 502);
// modbusSocket.setSoTimeout(10000);
modbus_out = new DataOutputStream(new BufferedOutputStream(modbusSocket.getOutputStream()));
modbus_in = new DataInputStream(new BufferedInputStream(modbusSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
//connection from client
if (in.available() > 0) {
//read Modbus bytes from client to get client request
System.out.println("===============Begin reading===============");
byte[] modbus_bytes = new byte[in.available()];
in.read(modbus_bytes);
System.out.println("Modbus request: ");
for (byte b : modbus_bytes) {
System.out.print(b);
}
System.out.println();
//transfer modbus request to modbus server
modbus_out.write(modbus_bytes);
modbus_out.flush();
System.out.println("Written to modbus server");
while (modbus_in.available() == 0) {
System.out.println("Waiting for device response...");
}
System.out.println("\nDevice response ready");
//get response from modbus server
modbus_bytes = new byte[modbus_in.available()];
modbus_in.read(modbus_bytes);
System.out.print("Modbus response: ");
for (byte b : modbus_bytes) {
System.out.print(b);
}
System.out.println("\nSending response to client");
//transfer response to client
out.write(modbus_bytes);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
//close TCP connection
try {
// in.close();
// out.close();
clientSocket.close();
modbusSocket.close();
System.out.println("===========Connection terminated==============");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Connection termination failed");
}
}
}

ServerSocket cannot read input from Client

I'm new to socket programming and I'm just trying out a few things. What I'm trying to do is have a Client that reads a text file, saves the lines from that file in an ArrayList and then send the lines to the Server. This is my code. The connection is successfully established, but when the server tries to read from his BufferedReader, it doesn't get anything:
Server:
import java.io.*;
import java.net.*;
public class Server extends Thread{
ServerSocket sock = null;
Socket client_sock = null;
PrintWriter out = null;
BufferedReader in = null;
Server(int port){
try{
sock = new ServerSocket(port);
}catch(IOException e){
System.out.println("Couldn't create server socket");
e.printStackTrace();
}
}
public void run(){
while (true){
try{
client_sock = sock.accept();
System.out.println("Successfully connected to client" + client_sock);
System.out.println(client_sock.getOutputStream());
System.out.println(client_sock.getInputStream());
out = new PrintWriter(client_sock.getOutputStream(),true);
//System.out.println(out);
in = new BufferedReader(new InputStreamReader(client_sock.getInputStream()));
//System.out.println(in);
System.out.println("Trying to read line sent from client:");
String l;
try{
l = in.readLine();
System.out.println(l);
}catch(IOException e){
System.out.println("Couldn't read line from client");
e.printStackTrace();}
}catch(IOException e){
e.printStackTrace();
break;
}
}
}
public static void main(String[] args){
//Thread t = new Server(Integer.parseInt(args[0]));
//t.start();
Server serv = new Server(10239);
System.out.println(serv.sock);
serv.run();
}
}
Client:
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
Socket sock = null;
OutputStream toServer = null;
PrintWriter out = null;
InputStream fromServer = null;
BufferedInputStream in = null;
Client(int port){
try{
sock = new Socket("localhost",port);
//System.out.println(sock.getPort());
//System.out.println(sock.getOutputStream());
//System.out.println(sock.getInputStream());
//toServer = sock.getOutputStream();
//System.out.println(sock.getOutputStream());
out = new PrintWriter(sock.getOutputStream());
//System.out.println(out);
//fromServer = sock.getInputStream();
in = new BufferedInputStream(sock.getInputStream());
//System.out.print(in);
}catch(UnknownHostException ue){
System.out.println("Host not known");
}
catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
Client client = new Client(Integer.parseInt(args[0]));
File f = new File("/Users/--------/Desktop/socket_test.txt");
BufferedReader f_in = null;
try{
f_in = new BufferedReader(new FileReader(f));
}catch(IOException e){
System.out.println("Cannot create FileReader for test file");
}
String line;
ArrayList<String> text = new ArrayList<String>();
try{
while ((line = f_in.readLine()) != null){
text.add(line);
}
}catch(IOException e){
e.printStackTrace();
}
//System.out.println("first line of file");
//System.out.println(text.get(0));
for (String l : text){
System.out.println("Sent the following line:");
System.out.println(l);
client.out.println(l);
}
}
}
This is the output I get for the Client:
Sent the following line:
Similar to the previous constructor
Sent the following line:
the InetAddress parameter specifies
Sent the following line:
the local IP address to bind to.
Sent the following line:
The InetAddress is used for servers that
Sent the following line:
may have multiple IP addresses
Sent the following line:
allowing the server to specify which of
Sent the following line:
its IP addresses to accept client requests on
and this for the Server:
ServerSocket[addr=0.0.0.0/0.0.0.0,localport=10239]
Successfully connected to clientSocket[addr=/127.0.0.1,port=58285,localport=10239]
Trying to read line sent from client:
null
I can't find the reason why this doesn't work, can anybody help me please?
Try to flush the stream after each line :
client.out.println(l);
client.out.flush();

DNS Interpreter through EchoClient

I have been trying to play around with Java's Socket class and I have hit a tough spot. I have three classes: EchoServerTemplate, ConcurrentServer, and EchoClient.
I want to send a website(www.google.com) from a client to the server and then have the server return the IP address. I think I am extremely close, but I do not know how BufferedStreamer in Java works well enough to figure out the error messages.
Here is my code for all three classes:
EchoServerTemplate (This is where I want the Web Address to be translated):
import java.net.*;
import java.io.*;
public class EchoServerTemplate extends Thread
{
public static final int DEFAULT_PORT = 6007;
public static final int BUFFER_SIZE = 256;
Socket clientSocket;
EchoServerTemplate(Socket cs){
clientSocket = cs;
}
public void run(){
InputStream fromClient = null;
OutputStream toClient = null;
byte[] buffer = new byte[BUFFER_SIZE];
String printaddress = null;
try {
while(true){
PrintWriter pout = new PrintWriter(clientSocket.getOutputStream(), true);
fromClient = new BufferedInputStream(clientSocket.getInputStream());
try {
InetAddress address = InetAddress.getByName(fromClient.toString());
printaddress = address.toString();
}
catch(UnknownHostException e){
System.out.println(e);
}
toClient = new BufferedOutputStream(clientSocket.getOutputStream());
while (printaddress != null) {
toClient.write(printaddress.getBytes("UTF-8"));
toClient.flush();
printaddress = null;
}
fromClient.close();
toClient.close();
clientSocket.close();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
ConcurrentServer:
import java.io.*;
import java.net.*;
public class ConcurrentServer {
public static final int BUFFER_SIZE = 256;
public static void main(String[] args) throws IOException {
try {
int serverPortNumber = 6007;
ServerSocket sock = new ServerSocket(serverPortNumber);
while (true) {
Socket clientSocket = sock.accept();
EchoServerTemplate thread = new EchoServerTemplate(clientSocket);
thread.start();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
EchoClient:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("127.0.0.1", 6007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: ");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to the host.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("IP Address: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
The task I accomplished before this was just having the ConcurrentServer repeat what was typed on the client. In modifying the code I may have accidentally messed something up. Here are the error messages I am receiving:
run: www.google.com Exception in thread "main"
java.net.SocketException: Connection reset at
java.net.SocketInputStream.read(SocketInputStream.java:189) at
java.net.SocketInputStream.read(SocketInputStream.java:121) at
sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283) at
sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325) at
sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177) at
java.io.InputStreamReader.read(InputStreamReader.java:184) at
java.io.BufferedReader.fill(BufferedReader.java:154) at
java.io.BufferedReader.readLine(BufferedReader.java:317) at
java.io.BufferedReader.readLine(BufferedReader.java:382) at
EchoClient.main(EchoClient.java:31) Java Result: 1 BUILD SUCCESSFUL
(total time: 4 seconds)
Any help is appreciated. If you need any more information, please let me know.

Is multithreading possible in a simple java server using udp connectionless protocol?

Is multi-threading possible in a simple java server using udp connectionless protocol? give an example!!
Multi-threading is actually simpler with UDP because you don't have to worry about connection state. Here is the listen loop from my server,
while(true){
try{
byte[] buf = new byte[2048];
DatagramPacket packet = new DatagramPacket( buf, buf.length, address );
socket.receive( packet );
threadPool.execute( new Request( this, socket, packet ));
.......
The threadPool is a ThreaPoolExecutor. Due to the short-lived nature of UDP sessions, thread pool is required to avoid the overhead of repeatedly thread creation.
Yes, it's possible through the use of the DatagramChannel class in java.nio. Here's a tutorial (It does not address the multithreading, but that is a separate issue anyway).
Here is one example try putting your own ip to get the hard-coded message back
package a.first;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Serv {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
Listner listner = new Listner();
Thread thread = new Thread(listner);
thread.start();
String messageStr = "Hello msg1";
int server_port = 2425;
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("172.20.88.223");
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local,
server_port);
System.out.println("about to send msg1");
s.send(p);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
messageStr = "Hello msg2";
msg_length = messageStr.length();
message = messageStr.getBytes();
p = new DatagramPacket(message, msg_length, local,
server_port);
System.out.println("about to send msg2");
s.send(p);
}
}
class Listner implements Runnable
{
#Override
public void run() {
String text = null;
while(true){
text = null;
int server_port = 2425;
byte[] message = new byte[1500];
DatagramPacket p = new DatagramPacket(message, message.length);
DatagramSocket s = null;
try{
s = new DatagramSocket(server_port);
}catch (SocketException e) {
e.printStackTrace();
System.out.println("Socket excep");
}
try {
s.receive(p);
}catch (IOException e) {
e.printStackTrace();
System.out.println("IO EXcept");
}
text = new String(message, 0, p.getLength());
System.out.println("message = "+text);
s.close();
}
}
}

Categories

Resources