Udp网络通讯之服务端:
public class receive{
public static void main(String[] args) throws IOException{
//创建接受端的socket对象
DatagramSocket ds = new DatagramSocket(12345);
while(ture){
//创建一个包袱/
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys,bys.lenth);
//接受数据
ds.receive(dp);
//解析数据
String ip = dp.getAddress().geiHostAddress();
String s = new String(dp.getData,0,do.getLenth);
//获得IP地址和传送的数据
}
}
}
UDP客户端发送数据 数据以键盘输入
public class client{
//创建发送端的对象
DatagramSocket ds = new DatagramSocket();
//封装键盘录入数据
BufferReader br = new BufferReader(new InputStreamReader(system.in));
String line =null;
while((line=br.readLine())!=null){
if(line.equal("886")) break;
byte[] bys=line.getBytes();
Datagrampacket dp= new Datagrampacket(bys,bys.Lenth,InetAddress.getByName("服务器 IP"),服务器端口号);
ds.sent(dp);
}
ds.close();
}
TCP 服务器 :
public class server {
//创建服务器对象
ServerSocket ss =new ServerSocket (9999);
Socket s =ss.accept();
//获取输入流
InputStream is = s.getIuputStream();
byte[] bys=new byte [1024];
int len=is.read(bys);
String ser= new String (bys,0,len);
OutputStream os = s.getOutputStream();
os.write("数据已经收到".getBytes());
s.close();
}
UDP客户端:
public class client{
Socket s =new Socket("服务器IP",“服务器端口”);
OutputStream os = s.getOutputStream();
os.write("你好服务器".getByte());
//获取输入流
InputStream is=s.getInputStream();
byte[] bys = new byte[1024];
int len= is.read(bys);
String cli= new String(bys,0,len);
s.close();
}