• 网络编程(二) 多线程


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

      

  • 相关阅读:
    DLL注入之Appinit_Dlls
    VC下遍历文件夹中的所有文件的几种方法
    Windows下C语言的Socket编程例子(TCP和UDP)
    Windows进程间共享内存通信实例
    window下线程同步之(Mutex(互斥器) )
    如何安装win10和linux [ubuntu14]双系统
    Windows虚拟地址转物理地址(原理+源码实现,附简单小工具)
    Windows驱动中通过MDL实现用户态与核心态共享内存
    C# Label显示多行文本及换行(WinForm/WebForm)
    使用delegate实现简单的查询功能
  • 原文地址:https://www.cnblogs.com/justphp/p/3602468.html
Copyright © 2020-2023  润新知