zoukankan      html  css  js  c++  java
  • 网络编程(二) 多线程

    入口:
    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(); } } }

      

  • 相关阅读:
    为什么button在设置标题时要用一个方法,而不像lable一样直接用一个属性
    桥接模式(透传模式)和直驱模式
    vb.net版机房收费系统——教你七层架构(三)—外观模式
    Android 4.4 KitKat NotificationManagerService使用具体解释与原理分析(二)__原理分析
    poj-2758 Checking the Text
    一种感悟,为什么努力了确还是死了一地
    一位程序员的6年总结(转)
    主键生成策略
    Linux下的crontab定时执行任务命令详解
    win7 64下安装mysql-python报错的解决办法
  • 原文地址:https://www.cnblogs.com/justphp/p/3602468.html
Copyright © 2011-2022 走看看