接收端:
class Receive
{
public static void main(String[] args)
{
DatagramSocket ds = new DatagramSocket(10000);创建接收端Socket
char[] arr = new char[1024];
DatagramPacket dp = new DatagramPacket(arr,arr.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
System.out.println("ip:"+ip+";port:"+port);
String text =new String (dp.getData(),0,dp.getLength());
System.out.println(text);
}
}
2.TCP传输
TCP两端的Socket,一个是客户端(Socket),一个是服务器(ServerSocket)
TCP连接是可靠的连接,连接是会经过三次握手,确保连接的正确。
客户端:
class Client
{
public static void main(String[] args)
{
Socket s = new Socket(8888);
OutputStream os = s.getOutputStream();
os.write("111111111".getBytes());
os.close();
}
}
服务器:
class Serve
{
public static void main(String[] args)
{
ServerSocket ss = new ServerSocket(10000);
Socket s = ss.accept();
String ip = s.getAddress().getHostAddress();
System.out.println("ip:"+ip);
InputStream is = s.getInputStream();
byte[] arr = new byte[1024];
int len = is.read(arr);
System.out.println(new String(arr,0,arr.length));
ss.close()
s.close()