UDP 多线程

UDP 多线程

收到消息

public class ChatReceice implements Runnable{

	     DatagramSocket socket;
	     private String   name;
	     private int    potrIP; 
	     
	  public  ChatReceice(int potrIP,String name){
		  this.name  =name;
		  this.potrIP=potrIP;
		  try {
			socket=new DatagramSocket(potrIP);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	  }
			public void run() {
				try {
			while(true){
				byte[] butter=new byte[2040];
				DatagramPacket packet=new DatagramPacket(butter, 0,butter.length);
				socket.receive(packet);
							//拆包 获得信息
				byte      [] data =packet.getData();
				String receivedata=new String(data,0,data.length);
                if(receivedata.equals("Bye")){
				socket.close();
				break;
				}
		else{
				System.out.println(this.name+":"+receivedata);
				}
			 }		
        } catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}finally {
					//先开后关
					socket.close();
					System.out.println("关闭了接口");
				}
			}
	  }

发送消息

public class ChatSends implements Runnable{
	    DatagramSocket socket ;
	    BufferedReader buffere;
	    DatagramPacket packet ;
        private String toIP   ;
        private int     toport; 
        private int     fromIP;
        public ChatSends(int toport,String toIp,int fromIP){
              this.toIP=toIp;     	
              this.toport=toport;  
              this.fromIP=fromIP;  
        	try {
				socket=new DatagramSocket(toport);
				buffere=new BufferedReader(new InputStreamReader(System.in));
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
 		public void run() {
 		    while(true){
 				try {
					String string=buffere.readLine();
					byte [] data=string.getBytes();
					packet= new DatagramPacket(data,0,data.length,new InetSocketAddress(this.toIP,this.fromIP));
					//发车
					socket.send(packet);
					if(string.equals("Bye")){
						break;
					}
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}finally {
					socket.close();
				}
 				
 		    }
 		    
 			socket.close();
 			}

		}

多线程

Student

public class ChatStudent {

	public static void main(String[] args) {
		new Thread(new ChatSends(1111,"127.0.0.1",3332)).start();
        new  Thread(new ChatReceice(8882, "老师")).start();
        //我是学生 我的端口号为88882 我要向端口号为33332的地址发送信息
	}

}

Teacher

public class ChatTeacher {

	public static void main(String[] args) {
		new Thread(new ChatSends(2222,"127.0.0.1",8882)).start();
        new  Thread(new ChatReceice(3332, "学生")).start();
      //我是老师 我的端口号为3332 我要向端口号为8882的地址发送信息
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值