javaTCP客户端和服务器的连接的简单代码(菜鸟日记)

TCPServer.java文件中:

import java.net.*;
import java.io.*;
public class TCPServer{
 public static void main(String args[]){
  InputStream in=null; OutputStream out=null;//定义输入流、输出流
  try{
   ServerSocket ss=new ServerSocket(5888); //初始化服务端
   Socket socket=ss.accept();                       //服务端和客户端相连
   in=socket.getInputStream();                     
   out=socket.getOutputStream();
   DataInputStream dis=new DataInputStream(in);             //服务器端得到客户端输入流
   DataOutputStream dos=new DataOutputStream(out);      //服务器端得到客户端输出流
   
   String s=null;
   if((s=dis.readUTF())!=null){
    System.out.println(s);
    System.out.println("from:"+socket.getInetAddress());          //获得IP地址
    System.out.println("Port:"+socket.getPort());                       //获得端口号
   }
   System.out.println(s);
   dos.writeUTF("h1,hello");
   dos.close();
   dis.close();
   socket.close();
  }catch(IOException e){
   e.printStackTrace();
  }
 }
}

TCPClient.java文件中:


import java.net.*;
import java.io.*;
public class TCPClient{
 public static void main(String args[]){
  InputStream is=null; OutputStream os=null;
  try{
   Socket socket=new Socket("localhost",5888);                  //定义客户端的IP和端口号
   is=socket.getInputStream();                                           
   os=socket.getOutputStream();
   DataInputStream dis=new DataInputStream(is);                    //输入流
   DataOutputStream dos=new DataOutputStream(os);              //输出流
   dos.writeUTF("hey");
   String s=null;
   if((s=dis.readUTF())!=null);
   System.out.println(s);
   dos.close();
   dis.close();
   socket.close();
  }catch (UnknownHostException e){
   e.printStackTrace();
  }catch(IOException e){
   e.printStackTrace();
  }
 }
}

运行时先运行服务器端再运行客户端。

原文地址:https://www.cnblogs.com/zhangxiaomo/p/3379648.html