Java advanced------programming based on socket low level network

Source: Internet
Author: User
Tags sin

[This is my own study notes, welcome reprint, but please specify the source:http://blog.csdn.net/jesson20121020]

Socket Communication:

The two programs on the network implement data interaction through a two-way communication connection, one end of the bidirectional link is called a socket. Sockets are typically used to connect clients and service parties. Sockets are a very popular programming interface for the TCP/IP protocol, and a socket is uniquely determined by an IP address and a port number.

In the traditional UNIX environment can operate TCP/IP protocol interface more than one socket, the socket is supported by the type of protocol is not only a TCP/IP, so there is no necessary connection between the two. In the Java environment, the socket is mainly based on TCP/IP protocol network programming.


the general process of socket communication:

The general connection process for Client/server programming with sockets is that the server side listen (listens) for a connection request on a port, and the client sends the server back to connect (connection request). The server sends back the Accept message to the client side. A connection is built up. Both the server side and client side can communicate with each other through methods such as Send,write.

For a full-featured socket, the following basic structure is included, and the work process consists of the following four basic steps:

(1). Create a 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.


To create a socket:

Java provides two classes of sockets and ServerSocket in java.net, respectively, to represent the client and server side of a two-way connection. This is a two well-encapsulated class that is easy to use and constructed as follows:

Socket (); Socket (proxy proxy); Socket (inetaddress address,int port); Socket (inetaddress address,int Port,boolean stream); Socket (String host,int port); Socket (String host,int Port,boolean stream); Socket (Socketinmpl impl); Socket (String host,int port,inetaddress localaddr,int localport); Socket (inetaddress address,int port,inetaddress localaddr,int localport); ServerSocket (); ServerSocket (int port); ServerSocket (int port,int backup); ServerSocket (int port,int backup,inetaddress bindaddr);

Where Address,host and port are the IP address, host name and port number 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 are the address of the local machine, Impl is the parent of the socket and can be used to create serversocket and to create sockets. Such as:

Socket client = new socket ("127.0.0.1", 2000);

ServerSocket Server = new ServerSocket (2000);

Note that when choosing a port, be careful that each port provides a specific service, only the correct port to obtain the appropriate services, 0~1023 for the system, such as the HTTP service port number 80,telent service port number 21, so when we select the port, It is best to choose a number greater than 1023 to prevent collisions.


client-to-server interaction with sockets:single Thread implementation:

If, the client and the server are single-threaded implementation of communication, each party can only send a message, that is, by: Client hair-server-server-client received .... This mode of communication, you can observe the following single-threaded implementation code output results:


Client code Sockettalkclient.java:

Package Com.jesson.mianshi.network;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.printwriter;import Java.net.socket;public class SocketTalkClient {/** * @ param args */public static void main (string[] args) {sockettalkclient client = new Sockettalkclient ();//test single-threaded implementations of clients interacting with the server SYSTEM.OUT.PRINTLN ("Client: Single thread ..."); Client.singlethreadtalkclient ();} /** * Single-threaded implementation of client-to-server communication */public void Singlethreadtalkclient () {try {socket socket = new Socket ("127.0.0.1", 4700);//Shanben 47 00 Port issue Customer request BufferedReader sin = new BufferedReader (new InputStreamReader (system.in));// The BufferedReader object is constructed by the system standard input device PrintWriter OS = new PrintWriter (Socket.getoutputstream ());//The output stream is obtained by the socket object, and constructs the PrintWriter object BufferedReader is = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));// The input stream is obtained by the socket object and the corresponding BufferedReader object is constructed string readline;readline = Sin.readline (); Reads a string from the system standard input while (!readline.equals ("Bye")) {os.println (ReadLine);//outputs the string read from the system standard input to SErveros.flush ();//flushes the output stream so that the Server immediately receives the string System.out.println ("Client:" + readline); try {System.out.println ("server:" + Is.readline ());} catch (IOException e) {readline = Sin.readline (); continue;} ReadLine = Sin.readline (); Reads a string from the system standard input}//Resume loop os.close (); Close the socket output stream is.close (); Close the socket input stream socket.close (); Close socket} catch (Exception e) {System.out.println ("error");}}}

Service-Side code Sockettalkserver.java:

Package Com.jesson.mianshi.network;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.printstream;import Java.io.printwriter;import Java.net.ServerSocket; Import Java.net.socket;public class Sockettalkserver {public static void main (string[] args) {Sockettalkserver Server = NE W sockettalkserver ();//test single-threaded implementation of client-to-server interaction System.out.println ("Servers: single-threaded ..."); Server.singlethreadtalkserver ( );} /** * Single-threaded implementation of client-to-server communication */public void Singlethreadtalkserver () {ServerSocket Server = null;try {server = new ServerSocket (47 00);} catch (IOException e) {//TODO auto-generated catch BlockSystem.out.println ("Can not listen to:" + e);} Socket socket = null;try {socket = server.accept ()} catch (IOException e) {//TODO auto-generated catch BLOCKSYSTEM.OUT.P Rintln ("Can not accept the socket from client:" + e);} String Line;try {BufferedReader is = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); PrintStream os = new PrintStream (SOCKET.GETOUTPUtstream ()); BufferedReader sin = new BufferedReader (new InputStreamReader (system.in)); SYSTEM.OUT.PRINTLN ("Client:" + is.readline ()), line = Sin.readline (), while (!line.equals ("Bye")) {os.println (line); O S.flush (); System.out.println ("Server:" + line); System.out.println ("Client:" + is.readline ()); line = Sin.readline ();} Os.close (); Is.close (); Socket.close (); Server.close ();} catch (IOException e) {//TODO auto-generated catch BlockSystem.out.println ("error:" + e);}}}
Program execution output results:

Client output:

Client: Single thread ... hello Serverclient:hello serverserver:hello cient I can only send one message at a time client: I can only send one message at a time. Server: Me, too.

Service-Side output:

<span style= "FONT-SIZE:14PX;" >server: Single thread ... client:hello serverhello cientserver:hello cientclient: I can only send one message at a time I am also server: I am also </span >

Multithreading implementations:

As can be seen, with a single-threaded implementation, the client can send only one message at a time, to realize that both parties may send any message, which requires the use of multiple threads, where two threads to implement listening and writing. The code is as follows:

Client code (SOCKETTALKCLIENT.JAVA):

Package Com.jesson.mianshi.network;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.printstream;import Java.io.printwriter;import Java.net.ServerSocket; Import Java.net.socket;public class Sockettalkserver {public static void main (string[] args) {Sockettalkserver Server = NE W sockettalkserver ();//test the multithreading implementation of the client-side interaction with the server SYSTEM.OUT.PRINTLN ("Server: Multithreaded ..."); Multithreadtalkserver ();} /** * Multithreaded implementation of client-side interaction with server */private void Multithreadtalkserver () {ServerSocket Server = null;try {server = new ServerSocket (47 01);} catch (IOException e) {//TODO auto-generated catch BlockSystem.out.println ("Can not listen to:" + e);} Socket socket = null;try {socket = server.accept ()} catch (IOException e) {//TODO auto-generated catch BLOCKSYSTEM.OUT.P Rintln ("Can not accept the socket from client:" + e);} String Line;try {BufferedReader is = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); PrintWriter os = new PrintWriter (SOCKET.GETOUTPUTStream ()); BufferedReader sin = new BufferedReader (new InputStreamReader (system.in)); new Serverlinstenthread (IS). Start (); new Serverwritethread (sin, os). Start ();/* * Os.close (); Is.close (); Socket.close (); Server.close (); */} catch (IOException e) {//TODO auto-generated catch BlockSystem.out.println ("error:" + e);}} /** * Service-side listening thread * * @author Jesson * */class Serverlinstenthread extends Thread {private BufferedReader linsten;public Serv Erlinstenthread (BufferedReader linsten) {//TODO auto-generated constructor stubthis.linsten = Linsten;} public void Run () {//TODO auto-generated method stubstring Clientinfo;try {while (true) {clientinfo = Linsten.readline (); SYSTEM.OUT.PRINTLN ("Client:" + clientinfo), if (Clientinfo.equals ("Bye")) {System.out.println ("Client downline, program exit"); System.exit (0);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} /** * Service End Write thread * * @author Jesson * */class Serverwritethread extends Thread {private BufferedReader writer;private Print WrITER Printwriter;public Serverwritethread (bufferedreader writer, printwriter printwriter) {this.writer = writer; This.printwriter = PrintWriter;} public void Run () {//TODO auto-generated method stubstring Serverinfo;try {while (true) {ServerInfo = Writer.readline ();p Rintwriter.println (ServerInfo);p Rintwriter.flush (); SYSTEM.OUT.PRINTLN ("server:" + serverinfo), if (Serverinfo.equals ("Bye")) {System.out.println ("server's own downline, program exit"); System.exit (0);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Service-side code (SOCKETTALKSERVER.JAVA):

Package Com.jesson.mianshi.network;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.printstream;import Java.io.printwriter;import Java.net.ServerSocket; Import Java.net.socket;public class Sockettalkserver {public static void main (string[] args) {Sockettalkserver Server = NE W sockettalkserver ();//test the multithreading implementation of the client-side interaction with the server SYSTEM.OUT.PRINTLN ("Server: Multithreaded ..."); Multithreadtalkserver ();} /** * Multithreaded implementation of client-side interaction with server */private void Multithreadtalkserver () {ServerSocket Server = null;try {server = new ServerSocket (47 01);} catch (IOException e) {//TODO auto-generated catch BlockSystem.out.println ("Can not listen to:" + e);} Socket socket = null;try {socket = server.accept ()} catch (IOException e) {//TODO auto-generated catch BLOCKSYSTEM.OUT.P Rintln ("Can not accept the socket from client:" + e);} String Line;try {BufferedReader is = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); PrintWriter os = new PrintWriter (SOCKET.GETOUTPUTStream ()); BufferedReader sin = new BufferedReader (new InputStreamReader (system.in)); new Serverlinstenthread (IS). Start (); new Serverwritethread (sin, os). Start ();/* * Os.close (); Is.close (); Socket.close (); Server.close (); */} catch (IOException e) {//TODO auto-generated catch BlockSystem.out.println ("error:" + e);}} /** * Service-side listening thread * * @author Jesson * */class Serverlinstenthread extends Thread {private BufferedReader linsten;public Serv Erlinstenthread (BufferedReader linsten) {//TODO auto-generated constructor stubthis.linsten = Linsten;} public void Run () {//TODO auto-generated method stubstring Clientinfo;try {while (true) {clientinfo = Linsten.readline (); SYSTEM.OUT.PRINTLN ("Client:" + clientinfo), if (Clientinfo.equals ("Bye")) {System.out.println ("Client downline, program exit"); System.exit (0);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} /** * Service End Write thread * * @author Jesson * */class Serverwritethread extends Thread {private BufferedReader writer;private Print WrITER Printwriter;public Serverwritethread (bufferedreader writer, printwriter printwriter) {this.writer = writer; This.printwriter = PrintWriter;} public void Run () {//TODO auto-generated method stubstring Serverinfo;try {while (true) {ServerInfo = Writer.readline ();p Rintwriter.println (ServerInfo);p Rintwriter.flush (); SYSTEM.OUT.PRINTLN ("server:" + serverinfo), if (Serverinfo.equals ("Bye")) {System.out.println ("server's own downline, program exit"); System.exit (0);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

Execute the above code and run the result:

Client output:

Client: Multi-threaded ..... Hello, serverclient: Hello, serverserver: Hello, Clientserver:server send more than one message: server:1. Abcdserver:  2.1234Server:  3. Abcclient send multiple messages: Client:client send more than one message: 1. Xxxxxclient:1. Xxxxx2.yyyyclient:2.yyyy3.zzzzclient:3.zzzzbyeclient:byeclient self-downline, program exit

Service-Side output:

Server: Multithreading ..... Client: Hello, Server hello, clientserver: Hello, Clientserver send multiple messages: Server:server send more than one message: 1. Abcdserver:1. ABCD 2. 1234Server:  2.1234 3. Abcserver:  3. Abcclient:client send multiple messages: client:1. Xxxxxclient:2.yyyyclient:3.zzzzclient:byeclient downline, program exit
  


Java advanced------programming based on socket low level network

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.