且构网

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

java 基TCP的多线程 网络编程

更新时间:2022-08-13 08:36:11

 

/*
在开发网络应用程序的时候  如果发送数据使用了  OutoutStream ->BufferedOutputStream 流的链接 那么 
 一定要在发送数据完成的时候 调用 flush或者 关闭链接流  否则 接收端可能接收不到数据  。。。
 直到缓冲区满了 数据才会发送出去 
*/
package me;
import java.net.* ;
import java.io.* ;
public class JavaNet extends Thread
{
  private Socket ss;
  public static void main(String []args)
  {

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

  JavaNet(Socket ss)  throws Exception
  {
    this.ss=ss ;
   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();
  }
public  void run()
  {

  }
  static public  void runServer()   //服务端
  {
    try
   {
     ServerSocket s1 = new ServerSocket(6666);
     while(true)
   {
     Socket ss=s1.accept() ;   //等待连接的到来
     new JavaNet(ss).start() ;
   }


   }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();
       }

 

 

  }

 

 

 


}