package demostrator;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPserver {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8888);
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
System.out.println("***Server will be start!***");
while (true) {
socket.receive(packet);
ServerThread thread = new ServerThread(packet,socket);
thread.start();
}
}
}
package demostrator;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ServerThread extends Thread {
DatagramPacket packet = null;
DatagramSocket socket = null;
ServerThread(DatagramPacket packet,DatagramSocket socket){
this.packet = packet;
this.socket = socket;
}
public void run(){
String info = new String(packet.getData());
//output info from client
System.out.println("i am server,client say: "+info);
InetAddress clientAddress = packet.getAddress();
int port = packet.getPort();
byte[] data1= "Welcome to server!~".getBytes();
DatagramPacket packet1 = new DatagramPacket(data1, data1.length, clientAddress, port);
try {
socket.send(packet1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package demostrator;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPclient {
public static void main(String[] args) throws IOException {
//get InetAddress of server
InetAddress add = InetAddress.getByName("localhost");
int port = 8888;
byte[] info = "usearname:wujun; password:416471".getBytes();
DatagramPacket packet = new DatagramPacket(info,info.length,add,port);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
//receive server infomation
byte[] serverMsg = new byte[1024];
DatagramPacket packet1 = new DatagramPacket(serverMsg, 0, serverMsg.length);
socket.receive(packet1);
String strServer = new String(serverMsg);
System.out.println("Server say:"+strServer);
socket.close();
}
}