文章目录
前言
两个UDP网络实例
一、UDP聊天
Sender:
package chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class talk implements Runnable {
DatagramSocket socket=null;
BufferedReader reader=null;
private String toIp;
private int Port;
private String fromIp;
public talk(String toIp, int port, String fromIp) {
this.toIp = toIp;
this.Port = port;
this.fromIp = fromIp;
try {
socket=new DatagramSocket(port);
reader=new BufferedReader(new InputStreamReader(System.in));
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
String msg=reader.readLine();
byte[] buffer=msg.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(this.toIp, this.Port));
socket.send(packet);
if (buffer.equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}finally {
socket.close();
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Receiver:
package chat;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class talkReceive implements Runnable {
DatagramSocket socket=null;
private int Port;
private String fromMsg;
public talkReceive(int port,String fromMsg) {
this.Port = port;
this.fromMsg=fromMsg;
try {
socket= new DatagramSocket(Port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
byte[] buffer=new byte[1024];
DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
byte[] datas=packet.getData();
String s = new String(datas, 0, datas.length);
System.out.println(fromMsg+"说:"+s);
if (s.equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}finally {
socket.close();
}
}
}
}
StudentTalk:
package chat;
public class talkStudent {
public static void main(String[] args) {
new Thread(new talk("localhost",8888,"7777")).start();
new Thread(new talkReceive(9000,"老师")).start();
}
}
TeacherTalk:
package chat;
import chat.talkReceive;
public class TeacherTalk {
public static void main(String[] args) {
new Thread(new talk("localhost",8888,"9000")).start();
new Thread(new talkReceive(7777,"老师")).start();
}
}
二、UDP下载文件
package threadTest;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlDown {
public static void main(String[] args) throws Exception {
URL url=new URL("目标");
HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=urlConnection.getInputStream();
FileOutputStream fos=new FileOutputStream("fileName");
byte[] buffer=new byte[1024];
int len=0;
while ((len=inputStream.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
inputStream.close();
urlConnection.disconnect();
}
}