package day23;
/*
编写一个聊天程序
有收数据的部分和发数据的部分
这两个部分同时进行
那iu索要用到多线程技术
一个线程控制收,一个线程控制发
因为收和发动作是不一致的,所以要定义连个run方法
而且这两哥方法要封装到不同的类中
*/
import java.io.*;
import java.net.*;
class Send implements Runnable //发送端
{
private DatagramSocket ds;
public Send(DatagramSocket ds)
{
this.ds=ds;
}
BufferedReader bufr =null;
public void run()
{
try
{
bufr =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line=bufr.readLine())!=null)
{
if("886".equals(line))
break;
byte[] buf = new byte[1024*64];
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.100"),10003);
ds.send(dp);
}
}
catch(Exception e)
{
throw new RuntimeException("发送失败");
}
finally
{
try
{
if(bufr !=null)
bufr.close();
}
catch(Exception e)
{
throw new RuntimeException("读取关闭失败");
}
}
}
}
class Receive implements Runnable
{
private DatagramSocket ds;
public Receive(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
byte[] buf = new byte[1024];
DatagramPacket dp =
new DatagramPacket(buf,buf.length);
String ip=dp.getAddress().getHostAddress();
String date = new String(dp.getData(),0,dp.getLength());//注意
System.out.println(ip+":"+date);
}
}
public class SendAndRecevie {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receiveSocket=new DatagramSocket(10003);
new Thread(new Send(sendSocket)).start();
new Thread(new Receive(receiveSocket)).start();
}
catch(Exception e)
{
throw new RuntimeException("聊天失败");
}
}
}
|