黑马程序员技术交流社区
标题:
udp 多线程演示
[打印本页]
作者:
fmi110
时间:
2015-10-7 10:22
标题:
udp 多线程演示
a
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class MutilThreadUdp {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
DatagramSocket ds1 = new DatagramSocket(8888);
DatagramSocket ds2 = new DatagramSocket(10888);
Udpsend send = new Udpsend( ds1);
Udpreceive re = new Udpreceive(ds2);
new Thread(re).start();
new Thread(send).start();
}
}
class Udpsend implements Runnable{
private DatagramSocket ds ;
public Udpsend(DatagramSocket ds) {
super();
this.ds = ds;
}
@Override
public void run() {
System.out.println("客户端跑起:");
BufferedReader br = null;
while(true){
br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
try {
while((line=br.readLine())!=null){
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,0,buf.length,
InetAddress.getByName("192.168.220.255"),10888);
System.out.println("Send message...:");
ds.send(dp);
if(line.equals("886"))
break;
}
break;
} catch (IOException e) {
e.printStackTrace();
}finally{
if(br!=null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
if(ds!=null)
ds.close();
}
}
}
}
class Udpreceive implements Runnable{
private DatagramSocket ds;
public Udpreceive(DatagramSocket ds) {
super();
this.ds = ds;
}
@Override
public void run() {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
System.out.println("服务器启动:");
while (true) {
try {
ds.receive(dp);
int len = dp.getLength();
int port = dp.getPort();
String ip = dp.getAddress().getHostAddress();
buf = dp.getData();
String message = new String(buf,0,len);
System.out.println(ip+" "+port+"发来信息:"+message);
if(message.equals("886"))
System.out.println(ip+" 下线");
// bos.write(buf, 0, len);
// System.out.println("字节数组输出流长度"+bos.size());
// bos.writeTo(System.out);
// bos.reset();
} catch (IOException e) {
throw new RuntimeException("接收失败");
}
}
}
}
复制代码
作者:
妖风小王子
时间:
2015-10-7 21:32
从哪里复制来的额
作者:
fmi110
时间:
2015-10-7 21:58
妖风小王子 发表于 2015-10-7 21:32
从哪里复制来的额
看笔记 然后自己打的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2