`

网络编程【四】UDP聊天

    博客分类:
  • Java
阅读更多
菜鸟练习UDP



运行效果图:
[img]

[/img]



/*

我的电脑的ip为:192.168.0.124
*/
import java.io.*;
import java.net.*;


class Send implements Runnable{
	private DatagramSocket ds;
	public Send(DatagramSocket ds){
		this.ds = ds;
	}
	@Override
	public void run() {
		try {
			BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
			String line;
			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.0.124"),10002);
				ds.send(dp);
				
			}
			ds.close();
		} catch (Exception e) {
		}
		
	}
	
}

class Rece implements Runnable{
	private DatagramSocket ds;
	public Rece( DatagramSocket ds){
		this.ds = ds;
	}
	@Override
	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 str = new String(dp.getData(),0,dp.getLength());
				System.out.println(ip+"----->"+str);
			}
		} catch (Exception e) {
		}
		
	}
}



public class ChatDemo {

	
	public static void main(String[] args) throws Exception{
		
		DatagramSocket sendSocket = new DatagramSocket();
		DatagramSocket receSocket = new DatagramSocket(10002);
		
		new Thread(new Send(sendSocket)).start();
		new Thread(new Rece(receSocket)).start();
		

	}

}
  • 大小: 28.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics