Stream Audio from Client to Server to Multiple Clients Java - java

As the title suggests I'm making an application that Streams audio from a client to a server where I store the audio and then distribute it to multiple clients to be played. I've got everything working up until the audio storage, but I can't seem to stream the audio to multiple clients.
Here is my attempt:
Server Code:
class Server {
static int port = 50005;
static int listen = 50010;
static int listenerPort = 50015;
static DatagramSocket serverSocket, listenSocket,
broadcastSocket;
static byte[] receiveData, listenData;
static DatagramPacket receivePacket, listenPacket;
static DataOutputStream out;
static ArrayList<String> listeners = new ArrayList<String>();
static File file = new File("recording.bin");
static boolean active = true;
public static void main(String args[]) throws Exception {
//Define the Receiving Datagram Socket
serverSocket = new DatagramSocket(port);
//Define the Timeout of the socket
serverSocket.setSoTimeout(10000);
//Define the listening socket
listenSocket = new DatagramSocket(listen);
listenSocket.setSoTimeout(10000);
//Define Broadcasting socket
broadcastSocket = new DatagramSocket();
//Define data size, 1400 is best sound rate so far
receiveData = new byte[1400];
listenData = new byte[256];
//Define the DatagramPacket object
receivePacket = new DatagramPacket(receiveData, receiveData.length);
listenPacket = new DatagramPacket(listenData, listenData.length);
//Prepare the DataOutputStream to write to file.
out = new DataOutputStream(new FileOutputStream(file));
//Write and Broadcast on a separate thread
Thread t = new Thread() {
#Override public void run() {
getPackets();
}
};
t.start();
//Set up Connection Listener on a separate thread
Thread l = new Thread() {
#Override public void run() {
listen();
}
};
l.start();
}
/***
* Function that gets the audio data packets
* saves them, and outputs the audio to the speakers.
*/
public static void getPackets() {
while (active) {
try {
//Wait until packet is received
serverSocket.receive(receivePacket);
System.out.println("Receiving Data");
//Write to Binary file
out.write(receiveData, 0, receiveData.length);
//Send data
sendData(receivePacket.getData());
} catch (IOException e) {
active = false;
//If connection times out close it
try {
out.close();
} catch (IOException t) {
//Do nothing
}
System.out.println("Converting to audio");
//Convert audio file
new Convert().toWAV();
}
}
}
/***
* Function that listens if there are any connections made to
* the listener port and creates a datagram socket to stream audio
* to anyone who connects
*/
public static void listen() {
while (active) {
try {
//Wait until packet is received
listenSocket.receive(listenPacket);
listeners.add(listenPacket.getAddress().getHostAddress());
System.out.println("Client received");
} catch (IOException e) {
if(active) {
listen();
}
}
}
}
public static void sendData(byte[] data) {
try {
for (int i = 0; i < listeners.size(); i++) {
InetAddress destination = InetAddress.getByName(listeners.get(i));
broadcastSocket.send(new DatagramPacket(data, data.length, destination, listenerPort));
System.out.println("Sending Data");
}
} catch (Exception e) {
//If it failed to send don't do anything
e.printStackTrace();
}
}
}
And here is the code I run on the multiple clients:
class Receiver {
static AudioInputStream ais;
static AudioFormat format;
static boolean active = true;
static int port = 50015;
static DatagramSocket serverSocket, socket;
static byte[] receiveData;
static DatagramPacket receivePacket, packet;
static ByteArrayInputStream bais;
static int sampleRate = 8000;
static int time = 10;
static DataLine.Info dataLineInfo;
static SourceDataLine sourceDataLine;
public static void main(String args[]) throws Exception {
socket = new DatagramSocket();
InetAddress destination = InetAddress.getByName("server ip address");
byte[] temp = new byte[256];
//putting buffer in the packet
packet = new DatagramPacket(temp, temp.length, destination, 50010);
socket.send(packet);
//Define the Receiving Datagram Socket
serverSocket = new DatagramSocket(port);
//Define data size, 1400 is best sound rate so far
receiveData = new byte[1400];
//Define the format sampleRate, Sample Size in Bits, Channels (Mono), Signed, Big Endian
format = new AudioFormat(sampleRate, 16, 1, true, false);
//Define the DatagramPacket object
receivePacket = new DatagramPacket(receiveData, receiveData.length);
//Prepare the Byte Array Input Stream
bais = new ByteArrayInputStream(receivePacket.getData());
//Now concert the Byte Array into an Audio Input Stream
ais = new AudioInputStream(bais, format, receivePacket.getLength());
//Define DataLineInfo
dataLineInfo = new DataLine.Info(SourceDataLine.class, format);
//Get the current Audio Line from the system
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
//Open up sourceDataLine and Start it
sourceDataLine.open(format);
sourceDataLine.start();
//Write and play on a separate thread
Thread t = new Thread() {
#Override
public void run() {
getPackets();
}
};
t.start();
//Now keep track of time
while (time > 0) {
time--;
Thread.sleep(1000);
if (time == 0) {
active = false;
}
}
//Close SourceDataLine
sourceDataLine.drain();
sourceDataLine.close();
}
/***
* Function that gets the audio data packets
* saves them, and outputs the audio to the speakers.
*/
public static void getPackets() {
try {
while (active) {
System.out.println("Receiving");
//Wait until packet is received
serverSocket.receive(receivePacket);
//Reset time
time = 10;
//Send data to speakers
toSpeaker(receivePacket.getData());
}
} catch (IOException e) {
}
}
/***
* Function that plays the sound bytes with the speakers.
* #param soundbytes = bytes of sound sent to speakers
*/
public static void toSpeaker(byte soundbytes[]) {
try {
sourceDataLine.write(soundbytes, 0, soundbytes.length);
} catch (Exception e) {
System.out.println("Not working in speakers...");
e.printStackTrace();
}
}
}
I've verified that the server does receive the initial connection which I use to get the clients ip address, but the client does not seem to receive any data, and I'm getting no errors on run time.
Any help would be much appreciated.

Ok so after messing around with this for a while I've realized the problem was not the code, but rather that the admins of the building's network where blocking me. So I'm going to go ahead and mark this as answered.

Related

Why does server process multiple clients at the same time when it's not multithreaded?

So in my code below i have a singlethreaded server and a multithreaded client. The reason for this is because i want the client to send packets and receive packets simultaneously. However when i start the server and run multiple clients the server can process multiple clients simultaneously even tough the server is not multithreaded? Can you explain this?
Server:
public class server {
public static void main(String[] args) throws IOException{
new server();
}
//declare the UDP server socket
DatagramSocket datagramSocket;
int port = 3741;
public server() throws IOException {
//create UDP server with a specific port number
datagramSocket = new DatagramSocket(port);
System.out.println("[UDP server] Datagram socket started on port " + port);
//prepare the packet structure for received packets
int dataLength = 100; //must be large enough so some part of packet doesn't get lost
byte[] receiveData = new byte[dataLength];
DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
while(true) {
datagramSocket.receive(packet);
System.out.println("client connected");
InetAddress inetAddress = packet.getAddress();
int clientPort = packet.getPort();
byte[] data = packet.getData();
//send response back to the client host
byte[] sendData = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(data, data.length, inetAddress, clientPort);
datagramSocket.send(datagramPacket); //sending data from server to client
}
}
}
Client:
public class client {
public static void main(String[] args) throws Exception {
new client();
}
public client() throws Exception{
DatagramSocket socket = new DatagramSocket();
InetAddress ip = InetAddress.getByName("127.0.0.1");
String message = "hello from client";
DatagramPacket packetSend = new DatagramPacket(message.getBytes(), message.getBytes().length, ip, 3741);
Thread th = new Thread(new Runnable() {
#Override
public void run() {
for(int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket.send(packetSend);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
th.start();
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//this part can't be in a thread because the loop above us will finish first before this starts
//we can put this code before the loop and start a thread this would also work
while(true) {
try {
socket.receive(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String data = new String(packet.getData()).trim();
System.out.println(data);
}
}
}
You think "the server can process multiple clients simultaneously even tough the server is not multithreaded" cause your brain cheat you. Acutually they are processing one by one in a reliatively fast speed. It's easy to see if you use wireshark or tcpdump to capture the server side packets. You will find the interesing truth.

How to create a listener for receiving data in Java socket

I need to send and receive data between a client and a server. The server will be managing multiple clients at once, so it needs to be able to send and receive data with little latency.
At the moment I can both send and receive data from the client to the server but it is done procedural, so if any data is lost the server will freeze until the client sends new data. The issue is that if the server is returning data then both the server and client will freeze, waiting for data from the other.
My current methods to receive and send data
public void run(){
while(true){
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("SERVER > " +new String(packet.getData()));
}
}
public void sendData(byte[] data){
DatagramPacket packet = new DatagramPacket(data, data.length, 6969);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
Ideally I would like something like ActionListener that can let me get an action whenever data is received. At the moment it will run a couple of ticks every time it receives data.
This is where the use of threads comes in. I'm not a big on java when it comes to coding but I think this will help you.
This is the server side code
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(8000);
while(true) {
Socket socket = s.accept();
HandleClient c = new HandleClient(socket);
Thread t = new Thread(c);
t.start();
}
}
HandleClient code
public class HandleClient implements Runnable{
Socket socket;
HandleClient(Socket socket){
this.socket = socket;
}
public void run() {
try{
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
double radius;
while(true){
radius = inputFromClient.readDouble();
double area = radius * radius * Math.PI;
outputToClient.writeDouble(area);
}
}catch(Exception e) {}
}
}
And client side
public static void main(String[] args){
try{
//System.out.println(add);
Socket socket = new Socket("localhost",8000);
Scanner input = new Scanner(System.in);
DataInputStream inputFromServer = new DataInputStream(socket.getInputStream());
DataOutputStream outputToServer = new DataOutputStream(socket.getOutputStream());
double radius;
System.out.println("Client running at IP address: "+socket.getLocalAddress().toString() +"and port number: "+socket.getLocalPort());
System.out.println("Enter the value of radius");
radius = input.nextDouble();
System.out.println("Writing input");
outputToServer.writeDouble(radius);
System.out.println(inputFromServer.readDouble());
}catch (Exception E){}
}
It's not the same as what you are working on but it's just a template to use threads to handle requests coming from clients. You can modify this to make your project work.

A problem about Java UDP communication with multi thread

I'm studying java network programming now and i wrote a program that the client sends 30 times current time to Server and the Server will create a new thread to parse the received UDP packet and give feedback to Client if Server receives the UDP packet.
The question is, after I run my code, the Server can receive the UDP packet and create a new thread, but it seems like DatagramSocket and DatagramPacket don't pass to the thread. Thence the thread can't give a feedback to Client and Client will wait all the time after send the first UDP packet.
My code is here:
Server
public class MulUDPServer {
public static void main(String[] args) {
DatagramSocket socket = null;
DatagramPacket receivedPacket;
final int PORT = 10010;
byte[] b = new byte[1024];
receivedPacket = new DatagramPacket(b, b.length);
try {
socket = new DatagramSocket(PORT);
System.out.println("Server start!");
while (true) {
// receive the packet from server
socket.receive(receivedPacket);
// to check if Server get the packet
System.out.println(new String(receivedPacket.getData(), 0, receivedPacket.getLength()));
// start the thread to handle the packet we have got
Thread thread = new Thread(new LogicThread(socket, receivedPacket));
thread.start();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// close the connection
socket.close();
} catch (Exception e) {
}
}
}
Thread
public class LogicThread implements Runnable {
DatagramSocket socket = null;
DatagramPacket receivedPacket = null;
public LogicThread(DatagramSocket socket, DatagramPacket receivedPacket) {
this.socket = socket;
this.receivedPacket = receivedPacket;
}
public void run() {
try {
// to test if a thread have been set up
System.out.println("a thread have been set up");
byte[] data = receivedPacket.getData();
int len = receivedPacket.getLength();
// get the client IP
InetAddress clientAddress = receivedPacket.getAddress();
// get the client port
int clientPort = receivedPacket.getPort();
// print the info about received packet
System.out.println("Client's IP:" + clientAddress.getHostAddress());
System.out.println("Client's port:" + clientPort);
System.out.println("The info:" + new String(data, 0, len));
// feedback to Client
byte[] b = "OK".getBytes();
DatagramPacket sendPacket = new DatagramPacket(b, b.length, clientAddress, clientPort);
// send
socket.send(sendPacket);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client
public class MulUDPClient {
public static void main(String[] args) {
DatagramSocket socket = null;
DatagramPacket sendPacket;
DatagramPacket receivedPacket;
String serverHost = "localhost";
int serverPort = 10010;
try {
socket = new DatagramSocket();
InetAddress address = InetAddress.getByName(serverHost);
byte[] b = new byte[1024];
receivedPacket = new DatagramPacket(b, b.length);
System.out.println("Client ready!");
for (int i = 0; i < 30; i++) {
// get the current time
Date d = new Date();
String content = d.toString();
byte[] data = content.getBytes();
sendPacket = new DatagramPacket(data, data.length, address, serverPort);
socket.send(sendPacket);
System.out.println("already send time");
Thread.sleep(10);
// receive packet from Server
socket.receive(receivedPacket);
byte[] response = receivedPacket.getData();
int len = receivedPacket.getLength();
String s = new String(response, 0, len);
System.out.println("the feedback from Server:" + s);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// close the connection
socket.close();
} catch (Exception e) {
}
}
}
}
the **Result** after run the Server and Client separately in two terminals:
Server
Server start!
Fri Nov 23 14:52:02 CST 2018
a thread have been set up
Client
Client ready!
already send time
From the result we can know, the Client have send a UDP packet and the Server parse it correctly and create a thread. Then the program is waiting...
It puzzle me a few days, Can anyone help me to solve it? :). Thanks!
Edit
Client
**CAN NOT** work
for (int i = 0; i < 30; i++) {
Thread writerWorker = new WriterWorker(socket);
writerWorker.start();
Thread readerWorker = new ReaderWorker(socket);
readerWorker.start();
}
**CAN** work
for (int i = 0; i < 30; i++) {
Date d = new Date();
String content = d.toString();
byte[] data = content.getBytes();
sendPacket = new DatagramPacket(data, data.length, address, serverPort);
socket.send(sendPacket);
Thread.sleep(10);
Thread readerWorker = new ReaderWorker(socket);
readerWorker.start();
}
WriterWorker
public class WriterWorker extends Thread {
DatagramSocket socket;
String serverHost = "localhost";
int serverPort = 10000;
DatagramPacket sendPacket;
public WriterWorker(DatagramSocket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
InetAddress address = InetAddress.getByName(serverHost);
Date d = new Date();
String content = d.toString();
byte[] data = content.getBytes();
sendPacket = new DatagramPacket(data, data.length, address, serverPort);
socket.send(sendPacket);
System.out.println("already send time");
} catch (Exception e) {
// TODO: handle exception
}
}
}
there is a flaw in your logic, when you do socket.receive(receivedPacket); this will let the worker wait until some datagramm packets does arrive...
the right way to handle asynchron communication via sockets would be the following (here an example for client side)
socket = new DatagramSocket();
Thread readerWorker = new ReaderWorker(socket);
readerWorker.start();
Thread writerWorker = new WriterWorker(socket);
writerWorker.start();
that way you would seperate reading and writing into different threads and the blocking methode socket.receive(...) would not stop your writing thread...
each worker would implement it's own worker loop
writer loop:
while(true){
if (sendPacket!= null){
socket.send(sendPacket);
}
Thread.sleep(10);
}
reader loop:
while(true){
socket.receive(receivedPacket);
handlePacket(receivedPacket);
}
NOTE:
that code was written totally out of my mind i didn't check proper syntax
delete the "Thread.sleep(10)" in client

Client-Server Based Audio Live Streaming in java using Socket

Given code is intended to do live audio streaming between client and server using java socket, but problem is that when I run this project, the client starts recording the sound and send it to receiver(server) side. Then Server buffers the received the sound but does not play it simultaneously.But when the client is closed, the server starts playing the sound.Please help me. I need that server must play received sound simultaneously.
\client
import java.io.*;
import java.net.*;
import java.sound.sampled.*;
import org.apache.commons.io.IOUtils;
public class ClientStream{
public ClientStream() throws IOException{
isl.runListener();
}
private IncomingSoundListener isl = new IncomingSoundListener();
AudioFormat format = getAudioFormat();
InputStream is;
Socket client;
String serverName = "192.168.2.8";
int port=3000;
boolean inVoice = true;
private AudioFormat getAudioFormat(){
float sampleRate = 16000.0F;
int sampleSizeBits = 16;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
return new AudioFormat(sampleRate, sampleSizeBits, channels, signed, bigEndian);
}
class IncomingSoundListener {
public void runListener(){
try{
System.out.println("Connecting to server:"+serverName+" Port:"+port);
client = new Socket(serverName,port);
System.out.println("Connected to: "+client.getRemoteSocketAddress());
System.out.println("Listening for incoming audio.");
DataLine.Info speakerInfo = new DataLine.Info(SourceDataLine.class,format);
SourceDataLine speaker = (SourceDataLine) AudioSystem.getLine(speakerInfo);
speaker.open(format);
speaker.start();
while(inVoice){
is = client.getInputStream();
byte[] data = IOUtils.toByteArray(is);
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais,format,data.length);
int bytesRead = 0;
if((bytesRead = ais.read(data)) != -1){
System.out.println("Writing to audio output.");
speaker.write(data,0,bytesRead);
// bais.reset();
}
ais.close();
bais.close();
}
speaker.drain();
speaker.close();
System.out.println("Stopped listening to incoming audio.");
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String [] args) throws IOException{
new ClientStream();
}
}
\server
import java.io.*;
import java.net.*;
import java.sound.sampled.*;
public class ServerStream {
private OutgoingSoudnListener osl = new OutgoingSoudnListener();
boolean outVoice = true;
AudioFormat format = getAudioFormat();
private ServerSocket serverSocket;
Socket server;
private AudioFormat getAudioFormat() {
float sampleRate = 16000.0F;
int sampleSizeBits = 16;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
return new AudioFormat(sampleRate, sampleSizeBits, channels, signed, bigEndian);
}
public ServerStream() throws IOException{
try{
System.out.println("Creating Socket...");
serverSocket = new ServerSocket(3000);
osl.runSender();
}catch(Exception e){
e.printStackTrace();
}
}
class OutgoingSoudnListener{
public void runSender(){
try{
server = serverSocket.accept();
System.out.println("Listening from mic.");
DataOutputStream out = new DataOutputStream(server.getOutputStream());
DataLine.Info micInfo = new DataLine.Info(TargetDataLine.class,format);
TargetDataLine mic = (TargetDataLine) AudioSystem.getLine(micInfo);
mic.open(format);
System.out.println("Mic open.");
byte tmpBuff[] = new byte[mic.getBufferSize()/5];
mic.start();
while(outVoice) {
System.out.println("Reading from mic.");
int count = mic.read(tmpBuff,0,tmpBuff.length);
if (count > 0){
System.out.println("Writing buffer to server.");
out.write(tmpBuff, 0, count);
}
}
mic.drain();
mic.close();
System.out.println("Stopped listening from mic.");
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main (String args[]) throws IOException{
new ServerStream();
}
}
Client-server connection and subsequently Socket is based on the TCP protocol model.
As you can confirm in their docs.
What you seek is DatagramSocket based on UDP, you might suffer the loss of packages but that's the way things work. That's how streaming video works, you get some, you lose some.
Now, you question per se, one of the problems you have while implementing with a TCP protocol is that TCP is based on acknowledgements in order to keep the communications synchronized, if either your server or client fails to acknowledge then you might experience the stream to get stuck, because of that.

Implementing a simple UDP network that continuously broadcasts to its neighbours

I have 3 nodes A, B and C with their respective port numbers.
I'm trying to write a java program that takes in 3 arguments:
its node name and its 2 neighboring node's ports and broadcasts a string "Hello I'm A" to them (so A would broadcast to B and C). It will do this every 3 seconds.
This program will be run in 3 separate instances.
Upon receiving a string it will print what node it has received it from "Received string" (example for Port B).
I have difficulties implementing this, I have heard of something called multicasting with UDP though. Here is my work so far, what am I doing wrong?
class UDP {
public static void main(String[] args) throws Exception {
String nodeName = args[0];
int neighbourPort1 = Integer.valueOf(args[1]);
int neighbourPort2 = Integer.valueOf(args[2]);
while(true) {
Thread.sleep(3000); //every 3 seconds
//Continously broadcast and listen to neighbour1
DatagramSocket socket1 = null;
try {
//CREATE SOCKET TO NEIGHBOUR1
InetAddress host = InetAddress.getByName("localhost");
socket1 = new DatagramSocket();
socket1.connect(host, neighbour1);
//CREATE DATAGRAMS FOR SENDING
String message = "Hello I'm " + nodeName;
byte[] sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, host, port);
socket1.send(sendPacket);
//CREATE DATAGRAMS FOR RECEIVING
byte[] receiveData = new byte[100]; //is there a way to determine the needed space?
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket1.receive(receivePacket);
System.out.println("Received string");
} catch(Exception e) { }
//Do the same for neighbour2, code is basically identical except for variables
DatagramSocket socket2 = null;
try {
//CREATE SOCKET TO NEIGHBOUR2
InetAddress host = InetAddress.getByName("localhost");
socket2 = new DatagramSocket();
socket2.connect(host, neighbour2);
//FOR SENDING DATAGRAMS
String message = "Hello I'm " + nodeName;
byte[] sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, host, port);
socket2.send(sendPacket);
//FOR RECEIVING DATAGRAMS
byte[] receiveData = new byte[100]; //is there a way to determine the needed space?
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket2.receive(receivePacket);
System.out.println("Received string");
} catch(Exception e) { }
}
}
}
I know I'm close to the solution. I'm able to broadcast properly but it's the constantly listening part that gets me.
I think its best to use a separate Thread to listen for data on your own port.
A sends data to B and blocks until it gets a packet from B.
B sends data to C and blocks until it gets a packet from C.
C sends data to A and blocks until it gets a packet from A.
Every node is waiting for each other. Just send the packets and wait 3 seconds.
The other thread is going to listen only.
public class UDP {
public static void main(String[] args) throws Exception {
final String nodeName = args[0];
final int ownPort = Integer.valueOf(args[1]);
final int neighbourPort1 = Integer.valueOf(args[2]);
final int neighbourPort2 = Integer.valueOf(args[3]);
// Don't create a new socket every time
DatagramSocket neighbour1 = new DatagramSocket();
DatagramSocket neighbour2 = new DatagramSocket();
neighbour1.connect(InetAddress.getLocalHost(), neighbourPort1);
neighbour2.connect(InetAddress.getLocalHost(), neighbourPort2);
// You have to LISTEN
new Thread() {
#Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(ownPort);
byte[] buffer = new byte[socket.getReceiveBufferSize()];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
// Blocks until it gets a packet
socket.receive(packet);
System.out.println("Received string");
}
// socket.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
}.start();
while (true) {
Thread.sleep(3000);
sendPacket(neighbour1, nodeName);
sendPacket(neighbour2, nodeName);
}
// If you're not using an infinite loop:
// neighbour1.close();
// neighbour2.close();
}
private static void sendPacket(DatagramSocket to, String from) throws Exception {
String message = "Hello I'm " + from;
byte[] data = message.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length);
to.send(packet);
}
}
Here is a simple frame for a server with two threads, one writing and one reading, place your network code at the right places.
package testing;
import java.util.Scanner;
public class ThreadTest {
public class MyListenerThread extends Thread {
#Override
public void run() {
/*
* Open Datagram ...
*/
while (true) {
/*
* Read data ...
*/
Scanner scanner = new Scanner(System.in);
System.out.println("read: " + scanner.next());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MySenderThread extends Thread {
#Override
public void run() {
/*
* Open Multicast ...
*/
while (true) {
/*
* Send ...
*/
System.out.println("Send ...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void start() {
MyListenerThread listener = new MyListenerThread();
MySenderThread sender = new MySenderThread();
listener.start();
sender.start();
}
public static void main(String[] args) {
ThreadTest server = new ThreadTest();
server.start();
}
}

Categories

Resources