这个代码是用线程实现建立连接
这样就可以实现发送和接受分离,大家互相不会影响到彼此
package com.udpcom;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
public class SendThread implements Runnable {
InetAddress ia;
int port;
DatagramPacket dp;
DatagramSocket ds;
Scanner in = new Scanner(System.in);
public SendThread(InetAddress ia, int port) {
this.ia = ia;
this.port = port;
try {
ds = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
do{
System.out.println("please input here:");
String str = in.nextLine();
//包装
dp = new DatagramPacket(str.getBytes(),str.getBytes().length,ia,port);
try {
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
}
}while(true);
}
}
package com.udpcom;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class ReceiveThread implements Runnable {
InetAddress ia;
int port;
DatagramPacket dp;
DatagramSocket ds;
byte buff[]=new byte[2014];
public ReceiveThread(int port) {
this.port = port;
dp = new DatagramPacket(buff,2014);
try {
ds =new DatagramSocket(port);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
do {
try {
ds.receive(dp);
System.out.println(new String(dp.getData(),0,dp.getLength()));
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}while(true);
}
}
package com.udpcom;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ClientA {
public static void main(String[] args) {
int port = 20000;
String ip = "localhost";
try {
InetAddress ia = InetAddress.getByName(ip);
Thread a = new Thread(new SendThread(ia,port));
Thread b = new Thread(new ReceiveThread(20001));
b.start();
a.start();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
package com.udpcom;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ClientB {
/**
* 只要输入对方的地址,加上一个端口号,我就可以发送
* 根据地址和端口号,包装成为数据报,然后利用套接字发送
* 发送利用20001 接受用20000端口,错开和另外一个main进程交互
*/
public static void main(String[] args) {
int port = 20000;
String ip = "localhost";
try {
InetAddress ia = InetAddress.getByName(ip);
Thread a = new Thread(new SendThread(ia,20001));
Thread b = new Thread(new ReceiveThread(port));
a.start();
b.start();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}