Reprint of Java socket programming instance

Source: Internet
Author: User
In fact, a simple understanding of network programming is that the two computers communicate with each other. for programmers, it is much easier to master a programming interface and use a programming model. java SDK provides some relatively simple APIs to complete these tasks. socket is one of them. for Java. these APIS exist in the java.net package. therefore, you only need to import this package to prepare network programming.
The basic network programming model is the client-to-server model. simply put, two processes communicate with each other, and one of them must provide a fixed location, while the other only needs to know the fixed location. and establish the connection between the two .. then you can complete the data communication. a fixed location is usually called a server, and a client is usually used to establish a connection. based on this simple model, you can access network programming.
JAVA supports many APIs for this model. here I just want to introduce the socket programming interface. java has simplified socket programming interfaces. first, we will discuss how the service provider that provides a fixed position is built. java provides serversocket for its support. in fact, when you create a powerful object of this class and provide a port resource, you have created a fixed location for other computers to access you. java code
  1. Serversocket Server = new serversocket (6789 );
ServerSocket server=new ServerSocket(6789);

Note that the port distribution must be unique, because the port is used to uniquely identify the unique service of each computer. In addition, the port number ranges from 0 ~ The first 65535 ports have been reserved by TCP/IP. Therefore, you can only allocate 1024 ports later than 1024. okay. we have a fixed position. now we need a connection line. this connection line is first requested by the customer. therefore, Java also provides a socket object to support it. you only need to create a socket Instance Object for support. java code

  1. Socket Client = new socket (inetaddress. getlocalhost (), 5678 );
Socket client=new Socket(InetAddress.getLocalHost(),5678);

The client must know the IP address of the server. at one point, Java also provides a related class inetaddress. the instance of this object must be provided through its static method. its static method mainly provides the method of obtaining the local IP address and directly obtaining the inetaddress through the name or IP address.
Okay. The above method can basically establish a line for the two computers to communicate with each other. But how is data transmitted? In fact, I/O operations are always closely related to network programming. because the underlying network continues data. unless called remotely, the core of troubleshooting is execution. otherwise, Data Interaction depends on Io operations. therefore, you must also import Java. io package. java Io operations are not complex. it provides readers and writers for byte streams and Unicode, and then provides a buffer for reading and writing data. java code

  1. Bufferedreader in =
  2. New bufferedreader (New inputstreamreader (server. getinputstream ()));
  3. Printwriter out = new printwriter (server. getoutputstream ());
BufferedReader in=new BufferedReader(new InputStreamReader(server.getInputStream())); PrintWriter out=new PrintWriter(server.getOutputStream()); 

The above two statements are used to create a buffer and convert the original byte stream to Unicode. the original byte stream comes from two methods of socket. getinputstream () and getoutputstream. used to obtain the input and output respectively. now we have basic models and basic operation tools. we can make a simple socket routine.
Service provider: Java code

  1. Import java. Io .*;
  2. Import java.net .*;
  3. Public class myserver {
  4. Public static void main (string [] ARGs) throws ioexception {
  5. Serversocket Server = new serversocket (5678 );
  6. Socket Client = server. Accept ();
  7. Bufferedreader in =
  8. New bufferedreader (New inputstreamreader (client. getinputstream ()));
  9. Printwriter out = new printwriter (client. getoutputstream ());
  10. While (true ){
  11. String STR = in. Readline ();
  12. System. Out. println (STR );
  13. Out. println ("has receive ....");
  14. Out. Flush ();
  15. If (Str. Equals ("end "))
  16. Break;
  17. }
  18. Client. Close ();
  19. }
  20. }
import java.io.*; import java.net.*; public class MyServer { public static void main(String[] args) throws IOException{ 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(); } } 

The main purpose of this program is that the server continuously receives the information written by the client only. the client will exit the program after sending the "end" string. and the server will also respond to "receive. inform the client that the message has been received.

Client code: Java code

  1. Import java.net .*;
  2. Import java. Io .*;
  3. Public class client {
  4. Static socket server;
  5. Public static void main (string [] ARGs) throws exception {
  6. Servers = new socket (inetaddress. getlocalhost (), 5678 );
  7. Bufferedreader in =
  8. New bufferedreader (New inputstreamreader (server. getinputstream ()));
  9. Printwriter out = new printwriter (server. getoutputstream ());
  10. Bufferedreader Wt = new bufferedreader (New inputstreamreader (system. In ));
  11. While (true ){
  12. String STR = wt. Readline ();
  13. Out. println (STR );
  14. Out. Flush ();
  15. If (Str. Equals ("end ")){
  16. Break;
  17. }
  18. System. Out. println (in. Readline ());
  19. }
  20. Server. Close ();
  21. }
  22. }
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 is to accept the customer's keyboard input, output the information, and then output "end" for exit identification.

This program is just a simple communication between two computers. What if multiple customers access one server at the same time? You can try to run another client and the result will throw an exception. How can we implement multiple clients?
In fact, after a simple analysis, we can see that the main channel for communication between customers and services is socket itself. the server agrees to establish communication with the customer through the accept method. in this way, when the customer establishes a socket. the server will also use this link for communication. so long as we have multiple connections. then our program can be changed to the following:

Server:

Java code
  1. Import java. Io .*;
  2. Import java.net .*;
  3. Public class myserver {
  4. Public static void main (string [] ARGs) throws ioexception {
  5. Serversocket Server = new serversocket (5678 );
  6. While (true ){
  7. Socket Client = server. Accept ();
  8. Bufferedreader in =
  9. New bufferedreader (New inputstreamreader (client. getinputstream ()));
  10. Printwriter out = new printwriter (client. getoutputstream ());
  11. While (true ){
  12. String STR = in. Readline ();
  13. System. Out. println (STR );
  14. Out. println ("has receive ....");
  15. Out. Flush ();
  16. If (Str. Equals ("end "))
  17. Break;
  18. }
  19. Client. Close ();
  20. }
  21. }
  22. }
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")) break; } client.close(); } } } 

Here, only an outer while loop is added. the purpose of this loop is to assign a socket to a customer when they come in until the customer completes an interaction with the server. Here, the customer's "end" message is received. now the interaction between multiple customers is realized. however. the problem comes again. although this solution solves multiple customers, it is executed in queue. that is to say, when a customer communicates with the server once, the next customer can come in and interact with the server. cannot achieve simultaneous service. so how can we achieve both communication and communication at the same time? Obviously this is a problem of parallel execution, so the thread is the best solution.
The following question is how to use the thread. the first thing to do is to create a thread and connect it to the network. then, the thread executes the operation. to create a thread, either directly inherit the thread or implement the runnable interface. to establish a connection with the socket, you only need to pass the reference. to execute the thread, you must override the run method. what the run method does. this is what the single-threaded version main did. so our program becomes like this: Java code

  1. Import java.net .*;
  2. Import java. Io .*;
  3. Public class multiuser extends thread {
  4. Private Socket Client;
  5. Public multiuser (socket c ){
  6. This. Client = C;
  7. }
  8. Public void run (){
  9. Try {
  10. Bufferedreader in =
  11. New bufferedreader (New inputstreamreader (client. getinputstream ()));
  12. Printwriter out = new printwriter (client. getoutputstream ());
  13. // Mutil user but can't parallel
  14. While (true ){
  15. String STR = in. Readline ();
  16. System. Out. println (STR );
  17. Out. println ("has receive ....");
  18. Out. Flush ();
  19. If (Str. Equals ("end "))
  20. Break;
  21. }
  22. Client. Close ();
  23. } Catch (ioexception ex ){
  24. } Finally {
  25. }
  26. }
  27. Public static void main (string [] ARGs) throws ioexception {
  28. Serversocket Server = new serversocket (5678 );
  29. While (true ){
  30. // Transfer Location change single user or Multi User
  31. Multiuser mu = new multiuser (server. Accept ());
  32. Mu. Start ();
  33. }
  34. }
  35. }
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")) break; } 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(); } } } 

My class is inherited directly from the Thread class. the constructor transmits the reference and establishes a connection with the customer socket. in this way, each thread will have it. A communication pipeline. similarly, we can enter the run method. hand over the previous operations to the thread for completion. in this way, the concurrent socket of multiple customers is established.

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.