黑马程序员技术交流社区
标题:
网络编程 多线程聊天
[打印本页]
作者:
fmi110
时间:
2015-8-12 09:36
标题:
网络编程 多线程聊天
网络编程
/*
多线程聊天模式:
*/
import java.io.*;
import java.net.*;
class Send implements Runnable //发送端
{
private DatagramSocket ds;
Send(DatagramSocket ds)
{
this.ds = ds;
}
public void run()
{
try
{
String line = null;
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
while((line = bufr.readLine())!=null)
{
if("886".equals(line))
break; //退出
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.31.248"),10002);//封装数据
System.out.println("消息已发出。。。");
ds.send(dp);
}
}
catch (Exception e)
{
System.out.println("发送失败");
System.out.println(e.toString());
}
finally
{
ds.close();
}
}
}
class Receive implements Runnable
{
private DatagramSocket ds;
Receive(DatagramSocket ds)
{
this.ds = ds;
}
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 text = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println("接收到新消息:");
System.out.println(ip+"_"+"port_"+port+": "+text);
}
}
catch (Exception e)
{
System.out.println("发送失败");
System.out.println(e.toString());
}
}
}
class UdpCommunicationDemo
{
public static void main(String[] args) throws Exception
{
DatagramSocket dsSend = new DatagramSocket(8888);
DatagramSocket dsRec = new DatagramSocket(10002);
new Thread(new Send(dsSend)).start();
new Thread(new Receive(dsRec)).start();
System.out.println("Hello World!");
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2