Multi-threaded network programming for Java Base TCP programming __

Source: Internet
Author: User

/*
When developing a Web application, if the data is sent using a link to the Outoutstream->bufferedoutputstream stream, then
Be sure to call flush when the data is sent or close the link stream otherwise the receiver may not receive the data ...
The data will not be sent until the buffer is full.
*/
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;
   INP Utstream in= Ss.getinputstream (); //Get input stream
   outputstream out=ss.getoutputstream (); //Get output stream
   out.write ("Hellow Welcome". GetBytes ()); //write data to output stream
   byte ch[] =new byte[100];< br>    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 ()   //service side
  {
    try
 &nbs P {
     serversocket s1 = new ServerSocket (6666);
     while (true)
   {
     Socket ss=s1.accept ();   /Waiting for the arrival of the connection
     new Javanet (ss). Start ();
  }


}catch (Exception e)
{
E.printstacktrace ();
}
}
static public void Runclient ()//Client
{
try{
Socket ss=new Socket (inetaddress.getbyname ("127.0.0.1"), 6666); Getbyname NULL returns local IP "LocalHost" returns local IP also returns local
OutputStream Out=ss.getoutputstream (); Get output flow to server write data
Out.write ("I am Zhangsan". GetBytes ());


}
catch (Exception e)
{
E.printstacktrace ();
}

}


}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.