Java Network Programming Common construction methods and methods of ServerSocket class and Socket class

Source: Internet
Author: User

Tag:server   address   ram    Connection    catch    readline   rem   com    service end    

Socket class
Socket (inetaddress address, int port)
Creates a stream socket and connects it to the specified port number for the specified IP address.
Socket (String host, int port)
Creates a stream socket and connects it to the specified port number on the specified host.
Socket (inetaddress address, int port, inetaddress localaddr, int localport)
Creates a socket and connects it to the specified remote port on the specified remote address.
Socket (String host, int port, inetaddress localaddr, int localport)
Creates a socket and connects it to the specified remote port on the specified remote host.

Close ()
close the socket.
Connect (socketaddress endpoint)
Connect This socket to the server.
Connect (socketaddress endpoint, int timeout)
Connect This socket to the server and specify a timeout value.
getinetaddress ()
returns the address of the socket connection.
getinputstream ()
returns the input stream for this socket.
getlocalport ()
returns the local port to which this socket is bound.
getoutputstream ()
returns the output stream for this socket.
getport ()
returns the remote port that this socket is connected to.


ServerSocket class
serversocket (int port)

accept ()
Listens for and accepts connections to this socket.
getinetaddress ()
Returns the local address of this server socket.

Socket programming Steps
The server-side creates the ServerSocket object and calls the accept method to return the Socket object
Client creates socket object , connects to server via port
Both the client and server use the getInputStream method and the Getoutputstream method in the socket to obtain the input stream and output stream for further data read and write operations.

(InetAddress used to describe the host address;
The socket is used to create a connection between two hosts;
ServerSocket is used to listen for requests from clients;
Sockets are often referred to as "sockets," which typically make a request to the network through a "socket" or answer a network request. )

Single server to multi-client
Server: Each time a client connects successfully, a thread is started to service it

Public class Server {
Public static void Main (string[] args) throws IOException {
ServerSocket ss = new ServerSocket (10086);
System.out.println ("Server starts normally ... ");
While (true) {
Socket socket = ss.accept ();
System.out.println ("User access successful ... ");
new Serverthread (socket). Start ();
}
}
}

Single server to multi-client

Client:

1 ImportJava.io.BufferedReader;2 Importjava.io.IOException;3 ImportJava.io.InputStreamReader;4 ImportJava.io.OutputStreamWriter;5 ImportJava.io.PrintWriter;6 Importjava.net.InetAddress;7 ImportJava.net.Socket;8 Importjava.net.UnknownHostException;9 ImportJava.util.Scanner;Ten  One  A  Public classClient { -     Private StaticPrintWriter pw=NULL; -     Private StaticBufferedReader br=NULL; the     Private StaticSocket S; -     StaticScanner scanner=NewScanner (system.in); -     /** -      * @paramargs +      */ -      Public Static voidMain (string[] args) { +         //TODO auto-generated Method Stub A         Try { atSocket s=NewSocket (Inetaddress.getlocalhost (), 5500); -pw=NewPrintWriter (NewOutputStreamWriter (S.getoutputstream ())); -Br=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); -              while(true){ -SYSTEM.OUT.PRINTLN ("Client side Please enter:"); -String str =Scanner.next (); in pw.println (str); - Pw.flush (); toString string=br.readline (); +SYSTEM.OUT.PRINTLN ("client read:" +string); -                 if(Str.equals ("Exit")){ the                      Break; *                 } $             } Panax Notoginseng}Catch(Exception e) { -                 //TODO auto-generated Catch block the e.printstacktrace (); +         } A         Try { the br.close (); + pw.close (); -}Catch(IOException E1) { $                 //TODO auto-generated Catch block $ e1.printstacktrace (); -         } -     } the}

Service side

ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.util.Scanner; Public classServer {Private StaticBufferedReader br=NULL; Private StaticPrintWriter pw=NULL; Private StaticServerSocket SS; Private StaticSocket S; StaticScanner scanner=NewScanner (system.in); /**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        Try{SS=NewServerSocket (5500); System.out.println (The server starts normally .... "); S=ss.accept ();//Blocking MethodsSYSTEM.OUT.PRINTLN ("Connection succeeded" +s.getremotesocketaddress ()); BR=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); PW=NewPrintWriter (NewOutputStreamWriter (S.getoutputstream ()));  while(true) {string string=Br.readline (); System.out.println ("Server read:" +string); System.out.println ("Server Side Please enter:"); String Str=Scanner.next ();                Pw.println (str);                Pw.flush (); if(Str.equals ("Exit")){                     Break; }            }        } Catch(Exception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); }        Try{pw.close ();        Br.close (); } Catch(IOException E1) {//TODO auto-generated Catch blockE1.printstacktrace (); }    }}

Java Network Programming Common construction methods and methods of ServerSocket class and Socket class

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.