Home » Java » Java network programming -UDP programming

Java network programming -UDP programming

DatagramSocket is using UDP communication, data transmission is not reliable.


The

// server thread


package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDP_ServerThread implements Runnable{
DatagramSocket ds;
public UDP_ServerThread (int port) {
// TODO Auto-generated constructor stub
{try
Ds=new DatagramSocket (port);
catch (SocketException E) {}
// TODO Auto-generated catch block
(e.printStackTrace);
}
}
@Override
public void (run) {
// TODO Auto-generated method stub
// accept packet
while (true) {
byte[] b=new byte[1024];
DatagramPacket dPacket=new DatagramPacket (B, b.length);
{try
Ds.receive (dPacket);
System.out.println ( "server received data is:" +new String (dPacket.getData), 0, dPacket.getLength (()));
catch (IOException E) {}
// TODO Auto-generated catch block
(e.printStackTrace);
}
}
}
}

// client thread


package udp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDP_ClientThread implements Runnable{
DatagramSocket ds;
public UDP_ClientThread (int port) {
// TODO Auto-generated constructor stub
{try
Ds=new DatagramSocket (port);
catch (SocketException E) {}
// TODO Auto-generated catch block
(e.printStackTrace);
}
}
@Override
public void (run) {
// TODO Auto-generated method stub
byte[] b=new byte[1024];
{try
InputStreamReader ir=new InputStreamReader (System.in);
BufferedReader br=new BufferedReader (IR);
String str;
while (((str=br.readLine)) {=null!)
DatagramPacket dPacket=new DatagramPacket (str.getBytes), str.length (InetAddress.getByName (), (localhost ), 8888);
Ds.send (dPacket);
}
(br.close);
(ir.close);
(ds.close);
catch (IOException E) {}
// TODO Auto-generated catch block
(e.printStackTrace);
}
}
}

The main method of

//

package udp;
public class {main
public static void main (String[] args) {
// TODO Auto-generated method stub
Thread thread=new Thread (new UDP_ServerThread (8888));
(thread.start);
Thread threadc=new Thread (new UDP_ClientThread (8889));
(threadc.start);
}
}

Latest