• 监听本机端口获取数据


    其实就是在本机建立一个server端监听这个端口,如下

    udpServer:

    package TTt;
    
    
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    
    
    public class UDPServer {
        public static void main(String args[]) throws Exception
        {
            //监听9876端口
           DatagramSocket serverSocket = new DatagramSocket(9876);
              byte[] receiveData = new byte[1024];
              byte[] sendData = new byte[1024];
              while(true)
                 {
                    //构造数据包接收数据
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    //接收数据
                    serverSocket.receive(receivePacket);
                    //解析数据
                    String sentence = new String( receivePacket.getData());
                    System.out.println("RECEIVED: " + sentence);
                 }
        }
    }

    TCpServer:

    package tcp;
    
    
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class Server {
         
           public static void main(String args[]) throws IOException {
              //为了简单起见,所有的异常信息都往外抛
              int port = 8898;
              //定义一个ServerSocket监听在端口8899上
              ServerSocket server = new ServerSocket(port);
              //server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
              Socket socket = server.accept();
              //跟客户端建立好连接之后,我们就可以获取socket的InputStream,并从中读取客户端发过来的信息了。
              Reader reader = new InputStreamReader(socket.getInputStream());
              char chars[] = new char[64];
              int len;
              StringBuilder sb = new StringBuilder();
              while ((len=reader.read(chars)) != -1) {
                 sb.append(new String(chars, 0, len));
              }
              System.out.println("from client: " + sb);
              
              reader.close();
              socket.close();
              server.close();
           }
           
        }
  • 相关阅读:
    BZOJ 1207
    Poj 2096 Collecting Bugs (概率DP求期望)
    HDU 5159 Card (概率求期望)
    HDU 4649 Professor Tian (概率DP)
    HDU 4652 Dice (概率DP)
    HDU5001 Walk(概率DP)
    C++中的 Round(),floor(),ceil()
    HDU 5245 Joyful(概率题求期望)
    poj 3071 Football (概率DP水题)
    关于一个群号分解的最大质数的求法
  • 原文地址:https://www.cnblogs.com/mynona/p/3603476.html
Copyright © 2020-2023  润新知