黑马程序员技术交流社区
标题:
分享一个聊天程序,收数据和发数据同时执行
[打印本页]
作者:
hrfhwy
时间:
2015-12-4 22:22
标题:
分享一个聊天程序,收数据和发数据同时执行
import java.net.*;
import java.io.*;
import java.util.*;
class DatagramSocketSystemin
{
public static void main(String[] args) throws Exception
{
DatagramSocket dssend=new DatagramSocket();
DatagramSocket dsrec=new DatagramSocket(10003);
new Thread(new DatagramSockets(dssend)).start();
new Thread(new DatagramSocketr(dsrec)).start();
}
}
class DatagramSockets implements Runnable
{
private DatagramSocket ds;
public DatagramSockets(DatagramSocket ds)
{
this.ds=ds;
}
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[] arr1=line.getBytes();
DatagramPacket dp=new DatagramPacket(arr1,arr1.length,InetAddress.getByName("192.168.1.255"),10003);
ds.send(dp);
}
}
catch (Exception ex)
{
}
}
}
class DatagramSocketr implements Runnable
{
private DatagramSocket ds;
public DatagramSocketr(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
while (true )
{
byte[] arr=new byte[1024];
DatagramPacket dp=new DatagramPacket(arr,arr.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
int port =dp.getPort();
System.out.println(ip+".."+port+".//...."+data);
}
}
catch (Exception ec)
{
throw new RuntimeException("jie shou shi ban ");
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2