Socket(网络套接字)是网络编程提供的一种机制,
通信的两端都要有socket,网络通信就是socket通信
数据在socket之间的io流通信
UDP通信
1.UDP服务器端创建
public class UdpServer {
public static void main(String[] args){
//create udp server
//must assign port first ,greater than 8000
DatagramSocket ds = null;
try {
ds = new DatagramSocket(12000);
//define receive byte array
//receive byte length
byte[] bs = new byte[1024];
DatagramPacket dp = new DatagramPacket(bs, bs.length);
//data package receive
ds.receive(dp);
InetAddress ia = dp.getAddress();
//get data
byte[] bs1 = dp.getData();
String data = new String(bs1,0, bs1.length);
System.out.println(ia.getHostAddress()+" get "+ data);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ds != null){
ds.close();
}
}
}
}
2.客户端创建
public class UdpClient {
public static void main(String[] args){
DatagramSocket ds =null;
try {
ds = new DatagramSocket();
//define
byte[] bs = "Hello".getBytes();
//create receiver port
InetAddress ia = InetAddress.getByName("192.168.1.6");
DatagramPacket dp = new DatagramPacket(bs,bs.length,ia, 12000);
//send
ds.send(dp);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ds != null){
ds.close();
}
}
}
}