Java Socket 服务端发送数据 客户端接收数据

时间:2022-08-28 23:37:30


import java.net.*;
import java.io.*;
/**
*客户端
*负责接收数据
*
*/
public class SocketClientTest {
  private static final String HOST="127.0.0.1";
  private static final int PORT=5209;

  private static void test(){
    Socket socket = null;
    DataInputStream dis = null;
    InputStream is = null;

    try{
      socket = new Socket(HOST,PORT);
      is = socket.getInputStream();
      dis = new DataInputStream(is);
      while(true){
          System.out.println("receive_msg:"+dis.readUTF());
      }
    }catch(Exception e){
      e.printStackTrace();
    }
  }

  public static void main(String[] args){

      test();
  }
}

----------------------------------------------------------------------------------------------------------------


import java.io.*;
import java.net.*;
/**
*服务端
*负责发送数据
*/
public class SocketServerTest {
  private static final int PORT = 5209;
  public static void test(){
    ServerSocket server = null;
    Socket socket = null;
    DataOutputStream out = null;
    try{
    server = new ServerSocket(PORT);
      socket = server.accept();
      out = new DataOutputStream(socket.getOutputStream());
      while(true){
        Thread.sleep(1000);
        out.writeUTF(getRandomStr());
        out.flush();
      }
    }catch(Exception e){
      e.printStackTrace();
    }
  }

  private static String getRandomStr(){
    String str = "";
    int ID = (int) (Math.random()*30);
    int x = (int) (Math.random()*200);
    int y = (int) (Math.random()*300);
    int z = (int) (Math.random()*10);
    str = "ID:"+ID+"/x:"+x+"/y:"+y+"/z:"+z;
    return str;
  }

  public static void main(String[] args){
    test();
  }
}