package 网络基础知识;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPServerSocket {
/*
* 2016/11/19
* 基于UDP的Socket
*/
public static void main(String[] args) {
//1.创建DatagramSocket,指定端口号
DatagramSocket socket;
try {
socket = new DatagramSocket(8888);
//2.创建DatagramPacket
byte[] bytes=new byte[1024];//创建字节数组
DatagramPacket dp=new DatagramPacket(bytes, bytes.length);
//3.接收客户端发送的数据信息
socket.receive(dp);//此方法在接受到数据报之前会一直阻塞
//4.读取数据
String info=new String(bytes,0,dp.getLength());
System.out.println("我是服务器,客户端说:"+info);
//向客户端响应信息
InetAddress address=dp.getAddress();
int port=dp.getPort();
byte[] data="欢迎您".getBytes();
DatagramPacket packet=new DatagramPacket(data, data.length, address, port);
socket.send(packet);
socket.close();
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package 网络基础知识;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;
public class UDPClientSocket {
/*
* 2016/11/19
* 基于UDP的Socket
*/
public static void main(String[] args) throws SocketException, UnknownHostException {
//1.定义发送信息
try {
InetAddress address=InetAddress.getByName("localhost");
int port=8888;
byte[] data="用户名:SYX;密码:999999".getBytes();
//2.创建DatagramPacket,包含要发送的对象
DatagramPacket dp=new DatagramPacket(data, data.length, address, port);
//3.创建datagramSocket
DatagramSocket socket=new DatagramSocket();
//4.发送数据
socket.send(dp);
byte[] bytes=new byte[1024];
DatagramPacket packet=new DatagramPacket(bytes, bytes.length);
socket.receive(packet);
System.out.println("我是客户端,服务器说:"+new String(bytes,0,packet.getLength()));
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}