发送端线程
package com.mysoft.socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* 以线程的方式发送数据
* @author bo
*
*/
public class UdpSend2 implements Runnable{
private DatagramSocket ds;
public UdpSend2(DatagramSocket ds){
this.ds = ds;
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line=br.readLine())!=null){
if("886".equals(line)){
break;
}
//将输入的数据发送出去
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("127.0.0.1"),10000);
ds.send(dp);
}
ds.close();
} catch (Exception e) {
throw new RuntimeException("发送数据失败!");
}
}
}
接收端现场
package com.mysoft.socket;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpRecv2 implements Runnable{
private DatagramSocket ds;
public UdpRecv2(DatagramSocket ds){
this.ds = ds;
}
@Override
public void run() {
try {
//服务端需一直开启,一有数据就接收
while(true){
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"----"+data);
}
} catch (Exception e) {
throw new RuntimeException("接收数据失败!");
}
}
}
main方法
package com.mysoft.socket;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpChartDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ss = new DatagramSocket();
DatagramSocket rs = new DatagramSocket(10000);
new Thread(new UdpSend2(ss)).start();
new Thread(new UdpRecv2(rs)).start();
}
}
报错信息:
Exception in thread "main" java.net.SocketException: Unrecognized Windows Sockets error: 0: Cannot bind
at java.net.PlainDatagramSocketImpl.bind0(Native Method)
at java.net.PlainDatagramSocketImpl.bind(PlainDatagramSocketImpl.java:82)
at java.net.DatagramSocket.bind(DatagramSocket.java:368)
at java.net.DatagramSocket.<init>(DatagramSocket.java:210)
at java.net.DatagramSocket.<init>(DatagramSocket.java:261)
at java.net.DatagramSocket.<init>(DatagramSocket.java:234)
真是不知何故,老师运行的好好的..我本地运行不起来..
|