网络传输需要一个服务器接收数据,然后客户端向服务器发送数据,UDP传输,把数据封装成数据包后传输。
下来看一段代码
客户端代码
import java.net.*;
public class Client{
public Client(){
try{
byte buf[] = new byte[200];
DatagramPacket willRecv = new DatagramPacket(buf,200);
DatagramSocket socket = new DatagramSocket();
InetAddress ip = InetAddress.getByName("127.0.0.1");
for(int i=0;i<10;i++){
String str ="www.itflight.net"+i;
DatagramPacket willsend = StringToPacket(str,ip,8000);
//发送数据包
socket.send(willsend);
//接受数据包
socket.receive(willRecv);
String message = PacketToString(willRecv);
System.out.println(message);
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
new Client();
}
//字符串转换为数据包,UDP传输使用
DatagramPacket StringToPacket(String message,InetAddress ip,int port){
int length = message.length();
byte buf[] = new byte[length];
buf = message.getBytes();
DatagramPacket rdp = new DatagramPacket(buf,0,length,ip,port);
return rdp;
}
String PacketToString(DatagramPacket dp){
int length = dp.getLength();
byte buf[] = new byte[length];
buf = dp.getData();
String str = new String(buf,0,length);
return str;
}
}
服务器端代码
import java.net.*;
public class Server{
public Server(){
try{
byte buf[] = new byte[200];
DatagramPacket willRecv = new DatagramPacket(buf,200);
DatagramSocket socket = new DatagramSocket(8000);
for(int i=0;i<10;i++){
//服务端先接受数据包
socket.receive(willRecv);
String message = PacketToString(willRecv);
System.out.println(message);
InetAddress ip = willRecv.getAddress();
int port = willRecv.getPort();
String str ="航班:"+i;
DatagramPacket willsend = StringToPacket(str,ip,port);
//发送数据包
socket.send(willsend);
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
new Server();
}
//字符串转换为数据包,UDP传输使用
DatagramPacket StringToPacket(String message,InetAddress ip,int port){
int length = message.length();
byte buf[] = new byte[length];
buf = message.getBytes();
DatagramPacket rdp = new DatagramPacket(buf,0,length,ip,port);
return rdp;
}
String PacketToString(DatagramPacket dp){
int length = dp.getLength();
byte buf[] = new byte[length];
buf = dp.getData();
String str = new String(buf,0,length);
return str;
}
}