标签:
先写接收端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpReceivve {
/**
* {@literal 接收端}
* @author xiaozhazi
* @throws IOException
*
*
*/
public static void main(String[] args) throws IOException {
//建立Socket服务,10001:接收端口,与发送端口对应;
DatagramSocket ds=new DatagramSocket(10001);
//定义接收包
byte[] buf =new byte[1024];
DatagramPacket dp= new DatagramPacket(buf, buf.length);
//通过Socket服务 接收数据包
ds.receive(dp);
//通过数据包获取数据
String ip =dp.getAddress().getHostAddress();
String data =new String(dp.getData(),0,dp.getLength());
int port =dp.getPort();
System.out.println(ip+"----------ip");
System.out.println(data+"----------data");
System.out.println(port+"----------port");
}
}
写客户端
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTcp {
/**
* @author xiaozhazi
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//1.create one ServerSocket and monitor the port
ServerSocket ss=new ServerSocket(10004);
//2.get the Socket that client-side send
Socket s=ss.accept();
//3.get the inputStream by socket
InputStream in =s.getInputStream();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"---has connected");
//4read the data
byte[] buf= new byte[1];
int len=-1;
while((len=in.read(buf))!=-1){
System.out.print(new String(buf, 0, len));
}
//close
s.close();
}
}
标签:
原文地址:http://www.cnblogs.com/zhazhenyu1992/p/5617899.html