|
package com.renxing.r0039_NetSeapk;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
//网络聊天程序
//1 接收端和发送端并存
//2 接收端不停的接受。
//3 发送端 当按下发送后 可以进行发送!
class JieShou implements Runnable
{
private DatagramSocket ds;
JieShou(DatagramSocket ds)
{
this.ds=ds;
}
@Override
public void run() {
//不停的接收 10000端口的数据
try {
//邮局(不停的接收邮件)
while(true)
{
//拆包
byte [] bys=new byte[1024];
DatagramPacket dp=new DatagramPacket(bys,bys.length);
//接收
ds.receive(dp);
//获取相关信息
String ip=dp.getAddress().getHostAddress();
String context=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"->>"+context);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Fasong implements Runnable
{
//发送端
private DatagramSocket ds;
Fasong(DatagramSocket ds)
{
this.ds=ds;
}
@Override
public void run() {
try {
//键盘录入
BufferedReader br=null;
DatagramPacket dp=null;
try
{
br=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while((line=br.readLine())!=null)
{
if("886".equals(line))
break;
//打成数据包
dp=new DatagramPacket(line.getBytes(),line.getBytes().length,InetAddress.getByName("localhost"),10000);
//发送
ds.send(dp);
}
ds.close();
}
catch(Exception e)
{
System.out.println("字节流读取错误");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Demo1
{
public static void main(String[] args) throws SocketException
{
//发送端
DatagramSocket ds=new DatagramSocket();
//接收端10000端口的数据
DatagramSocket ds2=new DatagramSocket(10000);
//同时开启2个线程!
new Thread(new Fasong(ds)).start();
new Thread(new JieShou(ds2)).start();
}
}
javaw.exe UDP 协议 同时开启2个线程
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|