• Java网络编程(TCP协议-服务端和客户端交互)


    客户端:

     1 package WebProgramingDemo;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 import java.io.OutputStream;
     6 import java.net.Socket;
     7 import java.net.UnknownHostException;
     8 
     9 public class SocketDemo {
    10 
    11     /**
    12      * @param args
    13      * @throws IOException 
    14      * @throws UnknownHostException 
    15      */
    16     public static void main(String[] args) throws  IOException {
    17 
    18         Socket s=new Socket("192.168.2.103",10002);
    19         OutputStream out=s.getOutputStream();
    20         out.write("Java".getBytes());
    21         InputStream is=s.getInputStream();
    22         byte buf[]=new byte[1024];
    23         int len=is.read(buf);
    24         System.out.println(new String(buf,0,len));
    25         s.close();
    26     }
    27 
    28 }

    服务端:

     1 package WebProgramingDemo;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 import java.io.OutputStream;
     6 import java.net.ServerSocket;
     7 import java.net.Socket;
     8 
     9 public class ServerSocketDemo {
    10 
    11     /**
    12      * @param args
    13      * @throws IOException
    14      */
    15     public static void main(String[] args) throws IOException {
    16 
    17         ServerSocket ss = new ServerSocket(10002);
    18         Socket s = ss.accept();
    19         String ip = s.getInetAddress().getHostAddress();
    20         System.out.println(ip + "....connected....");
    21         InputStream in = s.getInputStream();
    22         int len = 0;
    23         byte[] buf = new byte[1024];
    24         len = in.read(buf);
    25         System.out.println(new String(buf, 0, len));
    26         OutputStream os=s.getOutputStream();
    27         os.write("收到".getBytes());
    28         os.close();
    29         s.close();
    30         ss.close();
    31     }
    32 
    33 }
  • 相关阅读:
    execCommand快速实现复制到剪贴板
    webpack安装&指定版本安装&遇到的问题
    promise初体验
    使用原生JS发送AJAX请求(XML,JSON解析)
    【Python3】python中pymysql数据编码的问题
    闭包,闭包用途,call、apply、bind 的用法
    实现一个jQuery API
    Android 客户端和 web服务器通信
    Adb 基础
    在Android 中实现scp操作
  • 原文地址:https://www.cnblogs.com/ysw-go/p/5323357.html
Copyright © 2020-2023  润新知