Java Socket Communication BASIC programming complete Guide _java

Source: Internet
Author: User
Tags readline socket static class

What is a socket
two programs on the network realize the exchange of data through a two-way communication connection, one end of this two-way link is called a socket. The socket is typically used to implement a connection between the client and the service party. The socket is a very popular programming interface for the TCP/IP protocol, and a socket is uniquely determined by an IP address and a port number.
However, the type of protocol supported by the socket is not only TCP/IP, so there is no connection between the two. In the Java environment, socket programming mainly refers to the network programming based on TCP/IP protocol.

The process of socket communication
Server-side listen (listening) whether a port has a connection request, the client sends a connect request to the server side, and the server sends back the Accept (accepted) message to the client side. A connection is established. Both the server end and the client side can communicate with each other by means of send,write.
For a fully functional socket, include the following basic structure, which includes the following four basic steps:
(1) Create socket;
(2) Open the input/out stream connected to the socket;
(3) Read/write the socket according to a certain protocol;
(4) Close the socket. (In practice, not to use the display of closed, although many articles are recommended, but in my program, because the program itself is relatively simple, the requirements are not high, so did not cause any impact.) )


Create a socket
Java provides two classes of sockets and ServerSocket in Package java.net, respectively, to represent two-way connected clients and services. This is one of two very good packaged classes and is easy to use. The method is constructed as follows:

Socket (inetaddress address, int port);
Socket (inetaddress address, int port, Boolean stream);
Socket (String host, int prot);
Socket (String host, int prot, Boolean stream);
Socket (SocketImpl impl)
socket (String host, int port, inetaddress localaddr, int localport)
socket (inetaddress  address, int port, inetaddress localaddr, int localport)
serversocket (int port);
ServerSocket (int port, int backlog);
ServerSocket (int port, int backlog, inetaddress bindaddr)

Where address, host, and port are the IP addresses, host names, and port numbers of the other side of the two-way connection, stream indicates whether the socket is a stream socket or datagram Socket,localport the port number of the local host, LOCALADDR, and BINDADDR is the address of the local machine (the ServerSocket host address), Impl is the parent of the socket, which can be used to create serversocket and to create the socket. Count indicates the maximum number of connections that the server can support. For example: Learning video Network http://www.xxspw.com

Socket client = new Socket ("127.0.01.");
ServerSocket Server = new ServerSocket (80);

Note that you must be careful when choosing a port. Each port provides a specific service, and only the correct port is given to obtain the appropriate service. The port number for the 0~1023 is reserved for the system, for example, the port number of the HTTP service is the port number of the 80,telnet service is 23, so when we select the port number, it is best to select a number greater than 1023 to prevent conflicts.
If an error occurs when the socket is created, a ioexception is generated and must be processed in the program. So in creating a socket or serversocket you have to catch or throw an exception.

Code

Server

 Package socket; 
  Import java.io.*; 
   
  Import java.net.*; public class TCPServer {public static void main (string[] args) throws Exception {ServerSocket Server = new S 
      Erversocket (9091); 
        try {Socket client = server.accept ();  
          try {bufferedreader input = new BufferedReader (New InputStreamReader (Client.getinputstream ())); 
          Boolean flag = true; 
   
          int count = 1; while (flag) {SYSTEM.OUT.PRINTLN ("Client is going to start to stink, this is the first" + Count + "Times!") 
            "); 
             
            count++; 
            String line = Input.readline (); 
             
            SYSTEM.OUT.PRINTLN ("Client said:" + line); 
              if (Line.equals ("Exit")) {flag = false; SYSTEM.OUT.PRINTLN ("Client does not want to play!") 
            "); 
            else {SYSTEM.OUT.PRINTLN ("Client said:" + line); 
        }}} finally {Client.close (); }} finAlly {Server.close (); 
 } 
    } 
  }


Client

  Package socket; 
   
  Import java.io.*; 
  Import java.net.*; 
  Import Java.util.Scanner; 
   
  public class TcpClient {public 
    static void Main (string[] args) throws Exception { 
      Socket client = new Socket ("127 .0.0.1 ", 9091); 
      try { 
        PrintWriter output = 
            new PrintWriter (Client.getoutputstream (), true); 
        Scanner cin = new Scanner (system.in); 
        String words; 
   
        while (Cin.hasnext ()) { 
          words = Cin.nextline (); 
   
          OUTPUT.PRINTLN (words); 
   
          System.out.println ("writes out the data:" + words); 
        } 
   
        Cin.close (); 
      } finally { 
        client.close ();}}} 
   

Server-bound IP

C Write socket, struct SOCKADDR_IN structure can be specified sin_addr.s_addr, that is, you can specify the IP address, why there is such a demand, such as My network link is such:

I may only want to bind eth0 the IP address of this network adapter, because my lo and wlan0 may be using one port to do the Nginx virtual host, so when the server to open the ServerSocket, there is a need for the specified IP

Scheme
One of the ServerSocket constructors is as follows:

public ServerSocket (int port, int backlog, inetaddress bindaddr) throws IOException

Parameters:

Port-Local TCP port
Backlog-Listening backlog
BINDADDR-InetAddress to bind the server to


Because InetAddress has no constructors, I've been stuck here for a while, looking at StackOverflow, you can use the InetAddress Getbyname method

Sample code

  InetAddress Bindip = Inetaddress.getbyname ("192.168.1.168"); 
   
  ServerSocket Server = new ServerSocket (9091, 0, Bindip); 

Concurrent access
server-side by increasing the number of threads to handle multiple clients at the same time, in fact, the implementation is still very water, after all, Java for multithreaded encapsulation is good enough, I was on the server side with an internal class implementation of the Runnable interface, in the Run method to handle the client's request, Print out the data

Server code

Package capitalsocket; 
  Import Java.io.BufferedReader; 
  Import java.io.IOException; 
  Import Java.io.InputStreamReader; 
  Import java.net.InetAddress; 
  Import Java.net.ServerSocket; 
   
  Import Java.net.Socket; 
   
    public class Capitalizeserver {private static int clientnum = 0; public static void Main (String args[]) throws Exception {ServerSocket listener = new ServerSocket (9898, 0, Inetadd 
      Ress.getbyname ("192.168.1.168")); try {while (true) {Capitalizer Multip = new Capitalizer (Listener.accept (), CAPITALIZESERVER.CLIENTNU 
          m + +); 
          Thread t = new thread (MULTIP); 
        T.start (); 
      finally {listener.close (); 
      } private static Class Capitalizer implements Runnable {private Socket client; 
   
      private int id; 
        Public Capitalizer (Socket s, int id) {this.client = s; 
      This.id = ID; 
     public void Run () {   try {bufferedreader input = new BufferedReader (New InputStreamReader (this.client.getInputStr 
           
          EAM ())); 
             
            while (true) {String data = Input.readline (); 
              if (Data.equals ("Bye")) {System.out.println ("current First" + This.id + "client degree don't want to play!"); 
            Break 
            else {System.out.println ("current First" + This.id + "Client said:" + data); 
        A catch (IOException e) {e.printstacktrace ()); 
          Finally {try {this.client.close (); 
          catch (IOException e) {e.printstacktrace (); 
 } 
        } 
      } 
    } 
   
  }


Client code
The client code is basically unchanged, adding an exit operation

Package capitalsocket; 
   
  Import Java.io.PrintWriter; 
  Import Java.net.Socket; 
  Import Java.util.Scanner; 
   
  public class Capitalizeclient {public 
    static void Main (string[] args) throws Exception { 
      Socket client = new sock ET ("192.168.1.168", 9898); 
      try { 
        PrintWriter output = new PrintWriter (Client.getoutputstream (), true); 
        Scanner cin = new Scanner (system.in); 
        String words; 
   
        while (Cin.hasnext ()) { 
          words = Cin.nextline (); 
          OUTPUT.PRINTLN (words); 
           
          if (Words.equals ("Bye")) {break 
            ; 
          } 
           
          Every time you write data you need to sleep for a 
          thread.sleep (3000); 
        } 
   
        Cin.close (); 
      } finally { 
        client.close ();}}} 
   

Related Article

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.