网络编程(二) 多线程

入口:
package chat;

import java.net.DatagramSocket;
import java.net.SocketException;

public class chat {

	/**
	 * @param args
	 * @throws SocketException 
	 */
	public static void main(String[] args) throws SocketException {
		// TODO Auto-generated method stub
		DatagramSocket sd = new DatagramSocket();
		DatagramSocket re = new DatagramSocket(9000);
		
		send s = new send(sd);
		receive r = new receive(re);
		
		new Thread(s).start();
		new Thread(r).start();
	}

}



发送端: package chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class send implements Runnable { public DatagramSocket ds; public send(DatagramSocket ds) throws SocketException { this.ds = ds; } @Override public void run() { // TODO Auto-generated method stub try { InetAddress ip = InetAddress.getByName("192.168.1.255"); String line = null; //第三步:创建UDP数据包 System.out.println("开始聊天了:"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while((line=in.readLine())!=null) { byte[] buf = line.getBytes(); DatagramPacket dp = new DatagramPacket(buf, buf.length, ip, 9000); ds.send(dp); if("over".equals(line)) break; } ds.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 接收端: package chat; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class receive implements Runnable { public DatagramSocket ds; public receive(DatagramSocket ds) { this.ds = ds; } @Override public void run() { // TODO Auto-generated method stub try { byte[] buf = new byte[1024]; while(true) { DatagramPacket dp = new DatagramPacket(buf,buf.length); ds.receive(dp); //阻塞式 //第三步:解析接收到的udp包 String host = dp.getAddress().getHostName(); int port = dp.getPort(); String data = new String(dp.getData(),0,dp.getLength()); System.out.println("聊天内容是:"); System.out.println(host+":"+data); System.out.println(" "); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

  

posted @ 2014-03-15 20:41  justphp  阅读(230)  评论(0编辑  收藏  举报