zoukankan      html  css  js  c++  java
  • java TCP小程序

     1 package com.socket.tcp;
     2 
     3 import java.io.DataInputStream;
     4 import java.io.DataOutputStream;
     5 import java.io.IOException;
     6 import java.io.InputStream;
     7 import java.io.OutputStream;
     8 import java.net.ServerSocket;
     9 import java.net.Socket;
    10 import java.net.UnknownHostException;
    11 
    12 import org.junit.Test;
    13 
    14 public class TestTCP {
    15     @Test
    16     public void testTCPServer() {
    17         try {
    18             ServerSocket ss = new ServerSocket(9999);
    19             while (true) {// 需要不断的监听是否有客户端程序连接上来,所以需要不断地监控
    20                 Socket socket = ss.accept();//阻塞式方法
    21                 InputStream is = socket.getInputStream();
    22                 DataInputStream dis = new DataInputStream(is);
    23                 System.out.println(dis.readUTF());
    24             }
    25         } catch (IOException e) {
    26             e.printStackTrace();
    27         }
    28     }
    29 
    30     @Test
    31     public void testTCPClient() {
    32         try {
    33             Socket client = new Socket("127.0.0.1", 9999);
    34             OutputStream os = client.getOutputStream();
    35             DataOutputStream dos = new DataOutputStream(os);
    36             dos.writeUTF("Hello Server");
    37             dos.flush();
    38             dos.close();
    39 
    40         } catch (UnknownHostException e) {
    41             e.printStackTrace();
    42         } catch (IOException e) {
    43             e.printStackTrace();
    44         }
    45     }
    46 
    47 }
  • 相关阅读:
    write(byte[] b, int off, int len)
    getAttribute 与getParmeter 区别
    ServletContext
    SercletConfig 详解
    MYSQL导入数据出现ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
    mybatis在xml文件中处理大于号小于号的方法
    阿里云实名认证接口调试
    js encodeuricomponent base64
    Introspector内存溢出的原理解析
    JVM虚拟机工作原理
  • 原文地址:https://www.cnblogs.com/cjunj/p/2755761.html
Copyright © 2011-2022 走看看