且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

java 通过 socket 实现 服务器和客户端的通信 TCP

更新时间:2021-09-05 10:58:34

 // JBulder 9.0下执行

package me;
import java.net.* ;   //网络编程有关的类在此包
import java.io.* ;  //用到 输入输出流
public class JavaNet
{
  public static void main(String []args)
  {

     if(args.length>0)
       runServer() ;
       else
         runClient() ;

 

  }

  static public  void runServer()   //服务端
  {
    try
   {
     ServerSocket s1 = new ServerSocket(6666);
     while(true)
   {
     Socket ss=s1.accept() ;   //等待连接的到来
    InputStream in= ss.getInputStream() ;  //获得输入流
    OutputStream out=ss.getOutputStream() ;  //获得输出流
    out.write("hellow welcome".getBytes()) ;  //向输出流写入数据
    byte ch[] =new byte[100];
    int num=in.read(ch) ;
    System.out.println(new String(ch,0,num));
    in.close();
    out.close();
    ss.close();
   }


   }catch(Exception e)
   {
     e.printStackTrace();
   }
  }
 static  public void runClient()   //客户端
  {
       try{
         Socket ss=new Socket(InetAddress.getByName("127.0.0.1"),6666) ;   //getByname null返回本地IP   "LocalHost" 返回本地  IP也返回本地
         OutputStream out=ss.getOutputStream() ;  //获得输出流   向服务器写入数据
         out.write("I am  zhangsan ".getBytes());


       }
       catch (Exception e)
       {
         e.printStackTrace();
       }

 

 

  }

 

 

 


}