• java--网络编程


    1.Client端

    import java.net.* ;
    import java.io.* ;
    
    public class Client {
        public static void main(String[] args) throws Exception {
            
            Socket s = new Socket("localhost",8888);
            
            //向服务器发送消息
            InputStreamReader r = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(r);
            System.out.println("Input your want to write : " );
            String msg = br.readLine();
            
            OutputStream os = s.getOutputStream();
            
            DataOutputStream ds = new DataOutputStream(os);
            ds.writeUTF(msg);
            
            //接受来自服务器的消息
            InputStream r1 = s.getInputStream();
            DataInputStream dis = new DataInputStream(r1);
            String serverMsg = dis.readUTF();
            System.out.println("Reverse the Server massage is : " + serverMsg );
            
            br.close();
            s.close();
        }
    }

    2.Server端

     1 import java.net.*;
     2 import java.io.* ;
     3 
     4 public class Server {
     5     public static void main(String[] args) throws Exception {
     6         ServerSocket serverSocket = new ServerSocket(8888);
     7         while(true) {
     8             
     9             //接受客户端消息
    10             Socket socket = serverSocket.accept();
    11             System.out.println("a client connect this server !");
    12             InputStream r = socket.getInputStream();
    13         
    14             DataInputStream dis = new DataInputStream(r);
    15             String clientMsg = dis.readUTF();
    16             System.out.println("send to this server : " + clientMsg);
    17             
    18             //向客户端回复消息
    19             BufferedReader input = new BufferedReader(
    20                 new InputStreamReader(System.in)
    21             );
    22             String backMsg = input.readLine();
    23             OutputStream os = socket.getOutputStream();
    24             DataOutputStream dos = new DataOutputStream(os);
    25             dos.writeUTF(backMsg);
    26             input.close();
    27         }
    28     }
    29 }

    以上代码实现了点对点的通信。

    在网上看到了一篇文章讲的是网络编程UDP 实现点对点通信。http://computerdragon.blog.51cto.com/6235984/1194280这是网址,可以参考,讲的很详细。

  • 相关阅读:
    hive+mysql安装
    (转)hive sql 学习笔记(1)
    「CSPS 2020」动物园
    「CSPS 2019」Emiya 家今天的饭
    「CSPS 2020」儒略日
    「CSPS 2019」划分
    poj2251 Dungeon Master 搜索BFS
    poj1080 Human Gene Functions
    poj2349最小生成树prim算法
    hoj1356 Miller_Rabbin算法
  • 原文地址:https://www.cnblogs.com/xuewuzhijing95hao/p/7145100.html
Copyright © 2020-2023  润新知