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

      

  • 相关阅读:
    vector::reserve()对迭代器的影响
    C#日期格式转换大全
    aa
    C#中取到当前日期是在一年中的第几周
    EasyUI
    使用Ajax传递 json数据,并在一般处理页面进行接收全过程
    C#操作海量数据(Oracle、SQL Server)
    UE4教程
    游戏引擎的原理及应用
    C++基础02 (数组、函数、指针、结构体)
  • 原文地址:https://www.cnblogs.com/justphp/p/3602468.html
Copyright © 2011-2022 走看看