A good introduction Java Socket programming Article __ algorithm

Source: Internet
Author: User
Tags flush readline thread class

In fact, the simple understanding of network programming is that two computers communicate with each other. For programmers, it's much simpler to master a programming interface and use a programming model. The Java SDK provides some relatively simple APIs to do the work, and the socket is one of them.

for Java. These APIs exist within the package with java.net. So as long as you import this package, you can prepare the network programming. The basic model of network programming is the client to server model. Simply put, two processes communicate with each other, and one must provide a fixed position, while the other only needs to know the fixed position and establish the connection between the two. And then the data communication will be done. A fixed location is often referred to as a server, and a connection is often called a client. Based on this simple model, you can access network programming.

Java's support for this model has many kinds of APIs. And here I just want to introduce the programming interface for sockets. For Java, the programming interface of the socket has been simplified. Let's start with a discussion of how a service with a fixed location is built. Java provides serversocket to support it. In fact, when you create a power object for the class and provide a port resource, you create a fixed location that allows other computers to access you.

Java Code serversocket server=new serversocket (6789);

A little note here is that the distribution of the ports must be unique. Because the port is designed to uniquely identify the only service per computer. The other port number is from the 0~65535, the first 1024 ports have been TCP/IP as a reserved port, so you can allocate only 1024 ports.

All right. We have a fixed position. All that is needed now is a connection. The connection line is first made by the client. Therefore, Java also provides a socket object to support it. As long as the client creates an instance object for the socket to support it.

Java Code Socket client=new socket (inetaddress.getlocalhost (), 5678);

The client must know the IP address of the server. For a little Java also provides a related class inetaddress an instance of the object must be provided through its static method. Its static method mainly provides the method of getting inetaddress directly from native IP and by name or IP.

Well, the above method can basically build a line for the two computers to communicate with each other. But how does the data transfer? In fact, I/O operations are always related to network programming. Because the underlying network is the continuation of the data. Unless remote invocation, the core of the handling problem is on execution.

Otherwise, the interaction of the data is dependent on IO operations. So you also have to import java. IO this package. Java's IO operations are also not complex. It provides readers and writer for byte throttling and Unicode, and then provides a buffer for reading and writing to data.

Java Code BufferedReader in=new BufferedReader (New InputStreamReader (Server.getinputstream ())); PrintWriter out=new PrintWriter (Server.getoutputstream ());

BufferedReader in=new BufferedReader (New InputStreamReader (Server.getinputstream ())); 

The above two sentences are to create a buffer and the original byte flow into Unicode can be manipulated. The original byte stream is derived from two methods of the socket, getInputStream () and Getoutputstream (), respectively, for input and output. So now with the basic model and basic operation tools, we can do a simple socket routine to the service side:

Java code import java. Io. *;  import Java. Net *;    public class myserver   {  public static void Main (string[] args) throws IOException {&nbs P   ServerSocket server=new  serversocket (5678);    Socket client=server.accept ();    BufferedReader in=new BufferedReader (New InputStreamReader (Client.getinputstream ());    PrintWriter out= new     PrintWriter (Client.getoutputstream ());    while (true) {          String str=in.readline ();         System. Out println (str);         out. println ("has receive ...");         out. Flush ();         if (str. Equals ("End"))             break;    }     client. Close (); }  } 

Import Java. Io. *;
Import Java. Net *;

public class MyServer 
{public
 static void Main (string[] args) throws IOException {
  ServerSocket server=new< C5/>serversocket (5678);
  Socket client=server.accept ();
  BufferedReader in=new BufferedReader (New InputStreamReader (Client.getinputstream ()));
  PrintWriter out=new 
  PrintWriter (Client.getoutputstream ());
  while (true) {
       String str=in.readline ();
       System. Out println (str);
       Out println ("has receive ...");
       Out Flush ();
       if (str. Equals ("End"))
          ;
   Client Close ();
 } 
}

The main purpose of this program is for the server to continuously receive the information written by the client only. The client sends an "end" string to exit the program. And the server will also make "Receive" responses. Notifies the client that a message has been received. Client code:

Java Code Import java.net.*;  Import java.io.*;    public class client{  static Socket server;     public static void  main (string[] args) throws Exception {    server=new Socket (INETADDRESS.G Etlocalhost (), 5678);    BufferedReader in=new BufferedReader (new InputStreamReader (server). getInputStream ());    PrintWriter out=new    PrintWriter (Server.getoutputstream ());    BufferedReader wt=new BufferedReader (new     InputStreamReader (system.in));         while (true) {     String str=wt.readline ();     out.println (str);  & nbsp;  Out.flush ();     if (str.equals ("End")) {      break;     }     System.out.println (In.readline ());   }    server.close (); }  } 

Import java.net.*;
Import java.io.*;

public class client{
 static Socket server;
 
 public static void  main (string[] args) throws Exception {
  server=new Socket (Inetaddress.getlocalhost (), 5678);
  BufferedReader in=new BufferedReader (new InputStreamReader (server). getInputStream ()));
  PrintWriter out=new
  PrintWriter (Server.getoutputstream ());
  BufferedReader wt=new BufferedReader (New 
  InputStreamReader (system.in));
  
  while (true) {
   String str=wt.readline ();
   Out.println (str);
   Out.flush ();
   if (Str.equals ("End")) {break
    ;
   }
   System.out.println (In.readline ());
  }
  Server.close ();
 }

The client code accepts the client's keyboard input and outputs the information, and the output "end" is used to exit the identity. This program is just a simple communication between two computers. What if multiple customers are accessing a server at the same time? You can try running a client again, and the result is an exception. So how do multiple clients implement it?

In fact, a simple analysis, you can see that the main channel of customer and service communication is the socket itself. And the server through the Accept method is to agree to establish communication with the customer. This way when the client establishes the socket. The server will also use this link to communicate successively. So as long as we have more than one connection. Then our program can change to the following:

Server: Java code import java.io.*;  Import java.net.*;    public class MyServer {  public static void  Main (string[] args)   throws IOException {    ServerSocket server=new  serversocket (5678);  & nbsp while (true) {       Socket client=server.accept ();       BufferedReader in=new BufferedReader (New InputStreamReader (Client.getinputstream ());        PrintWriter out=new       printwriter (Client.getoutputstream ());        while (true) {          String str=in.readline ();           System.out.println (str);          OUT.PRINTLN ("has receive ...");          Out.flush ();           if (str.equals ("End"))   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;     break;     }       client. Close ();   } }  } 

Import java.io.*;
Import java.net.*;

public class MyServer {public
 static void  main (string[] args)  throws IOException {
  ServerSocket server =new  ServerSocket (5678);
  while (true) {
     Socket client=server.accept ();
     BufferedReader in=new BufferedReader (New InputStreamReader (Client.getinputstream ()));
     PrintWriter out=new
     PrintWriter (Client.getoutputstream ());
     while (true) {
        String str=in.readline ();
        System.out.println (str);
        OUT.PRINTLN ("has receive ...");
        Out.flush ();
        if (Str.equals ("End"))
          ;
     Client Close ();}}} 

This just adds an outer loop of the while loop. The purpose of this cycle is to have a client come in and assign it a socket until the client completes an interaction with the server, which is the "end" message that is accepted to the customer. So now it's time to have multiple customer interactions.

But the problem has come again, although it solves many clients, it is queued for execution. That is, when a client and server complete a communication, the next customer can come in and interact with the server. Can not be done at the same time service. So how can you achieve both communication and communication at the same time? Obviously this is a parallel implementation problem. So threading is the best solution.

So the question below is how to use threads. The first thing to do is to create a thread and make it accessible to the network connection. The thread then executes the action just now. To create a thread either directly inherits thread or implements the Runnable interface, it is possible to establish a connection with the socket as long as the reference is passed.

To execute a thread, you must override the Run method. And what the Run method does. It's just a single-threaded version of main. So our program turns out to be this:

Java Code Import java.net.*;  Import java.io.*;    public class multiuser extends thread{  private Socke T client;     Public multiuser (Socket c)   {    this. client=c; }     public void Run ()   {    try  {      & nbsp BufferedReader in=new BufferedReader (New InputStreamReader (Client.getinputstream ());     PrintWriter out=new     PrintWriter (Client.getoutputstream ());     //mutil User But can ' t parallel      while (true) {       String str=in.readline ();        System. Out.println (str);       out.println ("has receive ...");       Out.flush ();       if (str.equals ("End"))         break;      }     client.close ();   &nbsP }catch (IOException ex) {    }finally{          } }      public static void  main (string[] args) throws ioexception{    serversocket      Server=new ServerSocket (5678);    while (true)     {    //transfer Location      Change single User or Multi user     multiuser mu=new multiuser (server.accept ( );     Mu.start ();   } } } 

Import java.net.*;
Import java.io.*;

public class multiuser extends thread{
 private Socket client;
 
 Public multiuser (Socket C)
 {this
  . client=c;
 }
 
 public void Run ()
 {
  try  {   
   BufferedReader in=new bufferedreader (New InputStreamReader ( Client.getinputstream ()));
   PrintWriter out=new
   PrintWriter (Client.getoutputstream ());
    Mutil User but can ' t parallel while
    (true) {
     String str=in.readline ();
     System. Out.println (str);
     OUT.PRINTLN ("has receive ...");
     Out.flush ();
     if (Str.equals ("End"))
      ;
   Client.close ();  
 } catch (IOException ex) {
   }finally{
    
   }
 } public
 
 static void  main (string[] args) throws ioexception{
  serversocket 
  server=new serversocket (5678);
  while (true)
  {
   //transfer location change single 
   User or Multi User
   multiuser mu=new multiuser ( Server.accept ());
   Mu.start ();}}

The

My class inherits directly from the thread class. The connection is established through the constructor pass reference and customer socket. So that each thread has a communication pipeline. Also we can fill in the Run method. Give the previous operation to the thread to complete. So many client parallel sockets are built up.

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.