package 网络编程.通过多线程改进;
import javax.sound.midi.Receiver;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Maidemo {
public static void main(String[] args) throws SocketException {
DatagramSocket ds = new DatagramSocket();
DatagramSocket dst = new DatagramSocket(12306);
SendThread st = new SendThread(ds);
ReceiverThread rt = new ReceiverThread(dst);
Thread t1 =new Thread(st);
Thread t2 = new Thread(rt);
t1.start();
t2.start();
}
}
接收
package 网络编程.通过多线程改进;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceiverThread implements Runnable{
private DatagramSocket ds;
public ReceiverThread (DatagramSocket ds){
this.ds=ds;
}
@Override
public void run() {
try {
while (true){
byte[]bys = new byte[1024];
DatagramPacket dp =new DatagramPacket(bys,bys.length);
ds.receive(dp);
String s1 = new String(dp.getData(),0,dp.getLength());
System.out.println(s1+"---"+dp.getAddress().getHostAddress());
}
}catch (IOException e){
e.printStackTrace();
}
}
}
发送
package 网络编程.通过多线程改进;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class SendThread implements Runnable{
private DatagramSocket ds;
public SendThread (DatagramSocket ds){
this.ds=ds;
}
@Override
public void run() {
try {
Scanner scan = new Scanner(System.in);
while (true){
byte[] bys=scan.nextLine().getBytes();
DatagramPacket dp = new DatagramPacket(bys,bys.length,
InetAddress.getByName("192.168.0.102"),12306);
ds.send(dp);
}
}catch (IOException e){
e.printStackTrace();
}
}
}
未优化版
接受
package 网络编程;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Bec接受 {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(10086);
byte[]bys = new byte[1024];
int length = bys.length;
DatagramPacket dp = new DatagramPacket(bys,length);
ds.receive(dp);
InetAddress address = dp.getAddress();
String ip = address.getHostAddress();
byte[] bys2 =dp.getData();
int len = dp.getLength();
String s = new String(bys2,0,len);
System.out.println(ip+":"+s);
ds.close();
}
}
发送
package 网络编程;
import jdk.nashorn.internal.objects.DataPropertyDescriptor;
import java.io.IOException;
import java.net.*;
import java.nio.channels.DatagramChannel;
import java.util.Scanner;
public class Maindemo {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
DatagramSocket ds = new DatagramSocket();
byte[] bys=scan.next().getBytes();
int length = bys.length;
InetAddress address =InetAddress.getByName("192.168.0.102");
int port = 10086;
DatagramPacket dp =new DatagramPacket(bys,length,address,port);
ds.send(dp);
ds.close();
}
}
|