基于udp的socket编程小例子之使用多线程进行通信

package udpDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Send implements Runnable{
	private DatagramSocket ds;
	public Send(DatagramSocket ds)
	{
		this.ds=ds;
	}
	public void run() {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in)) ;
		String line=null;
		try {
			while( (line=br.readLine())!=null)
			{
				if("886".equals(line))
				{
					break;
				}
			  byte []data=line.getBytes();
			  DatagramPacket dg=new DatagramPacket(data,data.length,InetAddress.getByName("10.5.83.255"),10001);
			  this.ds.send(dg);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("发送端失败.....");
			e.printStackTrace();
		}
		
	}


}

	

package udpDemo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Rece implements Runnable{
	private DatagramSocket ds;
	public Rece(DatagramSocket ds)
	{
		this.ds=ds;
	}
	public void run() {
		  byte []data=new byte[1024];
		  DatagramPacket dp=new DatagramPacket(data,data.length);
		while(true)
		{
		
		 try {
			ds.receive(dp);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  String ip= dp.getAddress().getHostAddress();//获取ip地址
		  String line=new String(data,0,dp.getLength());
		  System.out.println("ip:"+ip+",data:"+line);
		}
		
	}
}

package udpDemo;

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

/*
编写聊天程序,有收数据的部分, 和发数据的部分。
需要用到多线程技术,一个线程负责收,另外一个线程负责收
因为收和发动作 是不一致的,所以定义两个run方法。
*/
public class chartDemo {
 public static void main(String[] args) {
	try {
		DatagramSocket sendsocket=new DatagramSocket();
		DatagramSocket recesocket=new DatagramSocket(10001);
		new Thread(new Send(sendsocket)).start();
		new Thread(new Rece(recesocket)).start();
	} catch (SocketException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}

你可能感兴趣的:(基于udp的socket编程小例子之使用多线程进行通信)