bsp; //获取接收的数据长度
int length=dp.getLength();
//获取发送端的IP地址
String ip=dp.getAddress().getHostAddress();
//获取发送端的端口号
int port =dp.getPort();
System.out.println("ip地址为:"+ip+"端口号为:"+port+"发送的内容为:"+new String(bytes,0,length));
}
}
四、TCP通信:
1、ServerSocket类:服务器端;Socket类:客户端。
//客户端
public class TCPClient {
public static void main(String[] args) throws UnknownHostException, IOException {
//1.创建Socket对象,明确要连接的服务器地址和端口号
Socket socket =new Socket("127.0.0.1",8888);
//2.明确数据源
FileInputStream fis=new FileInputStream("D:\\java\\a.txt");
//3.从socke对象中获取字节输出流,准备把读的文件字节写给服务器
OutputStream out=socket.getOutputStream();
//4.开始复制
int len=0;
byte[] bytes=new byte[1024];
while((len=fis.read(bytes))!=-1){
out.write(bytes,0,len);
}
//结束输出流,告诉服务器结束了,不要读了
socket.shutdownOutput();
//接收服务器的回复
//1.从socket对象中获取字节输入流,接收服务器回复的数据
InputStream in=socket.getInputStream();
len=in.read(bytes);
System.out.println(new String(bytes,0,len));
//释放资源
socket.close();
fis.close();
}
}
2、多线程传输:
//线程任务对象
public class Upload implements Runnable {
private Socket socket;
public Upload() {
};
public Upload(Socket socket) {
this.socket = socket;
};
public void run() {
FileOutputStream fos = null;
try {
// 3.明确目的地
File file = new File("D:\\nihao");
// 如果该目录不存在则创建
if (!file.exists()) {
file.mkdirs();
}
String filename = "oracle" + System.currentTimeMillis() + ".txt";
// 明确目的地
fos = new FileOutputStream(file + File.separator + filename);
// 明确数据源
InputStream in = socket.getInputStream();
// 开始复制
int len = 0;
byte[] bytes = new byte[1024];
while ((len = in.read(bytes)) != -1) {
fos.wri