- 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;
- /**socket聊天程序
- * @author Administrator
- *
- */
- public class datagramSocketDemo {
- /**
- * @param args
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- sendDemo send = new sendDemo(new DatagramSocket());//发送端
- new Thread(send).start();
- receDemo rece = new receDemo(new DatagramSocket(10011));//接收端
- new Thread(rece).start();
-
- }
- }
- class sendDemo implements Runnable{
- DatagramSocket ds = null;
- sendDemo(DatagramSocket ds){
- this.ds = ds;
- }
- public void run(){
- BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
- String s = null;
- try {
- while((s=buf.readLine())!=null){
- if(s.equals("886"))
- break;
- byte[]by = s.getBytes();
- DatagramPacket dp = new DatagramPacket(by, by.length,InetAddress.getByName("192.168.3.102"),10011);
- ds.send(dp);
- }
- ds.close();
- buf.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- class receDemo implements Runnable{
- DatagramSocket ds =null;
- public receDemo(DatagramSocket ds) {
- this.ds = ds;
- }
- public void run(){
- while(true){
- byte[]by = new byte[1024];
- DatagramPacket dp = new DatagramPacket(by,0,by.length);
- try {
- ds.receive(dp);
- String data = new String(dp.getData(),0,dp.getLength());
- String ip = dp.getAddress().getHostAddress();
- System.out.println(ip+" : "+data);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
-
- }
复制代码 我只为了黑马币
|
|