Java:socket Communication

Source: Internet
Author: User

Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests. ServerSocket is used for server-side, socket is used when establishing network connection. When the connection succeeds, a socket instance is generated at both ends of the application, manipulating the instance to complete the required session. For a network connection, sockets are equal, and there is no difference, not due to different levels on the server side or on the client. The connection process between sockets can be divided into three steps: Server listening, client request, connection acknowledgement.

Example one: Socket communication based on TCP/IP protocol:

package z_test_socket_demo;import java.io.ioexception;import Java.io.OutputStream; Import Java.net.serversocket;import Java.net.socket;public class Testserversocket {public static void main (string[] args) {//TODO auto-generated method stub serversocket serversocket = null; Socket socket = Null;outputstream OutputStream = null;try {serversocket = new ServerSocket (8888);//Specify Listening port System.out.prin TLN ("==>> accepting"); socket = Serversocket.accept (); Listen for client's request, method block, request succeeds, return socket object outputstream = Socket.getoutputstream (); Gets the output stream string string = "==>> Hello client,this is a message from server"; Send something to the client. byte[] buffer = string.getbytes (); outputstream.write (buffer); Outputstream.flush ();} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();} finally {try {serversocket.close (); Socket.close (); O Utputstream.close ();} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();}}} 
Package Z_test_socket_demo;import Java.io.ioexception;import Java.io.inputstream;import java.net.InetAddress; Import Java.net.socket;import Java.net.unknownhostexception;public class Testclientsocket {public static void main ( String[] args) {//TODO auto-generated method stub socket sockets = Null;inputstream InputStream = null;try {//socket = new Socket (inetaddre Ss.getlocalhost (), 8888);//request to connect to the server's 8888 port, the construction method can usually specify the IP address socket = new Socket ("10.25.26.141", 8888); InputStream = Socket.getinputstream (); Get input stream byte[] buffer = new Byte[64];int temp = 0;while ((temp = inputstream.read (buffer))! =-1) {//reads data into a byte array, this method blocks Syst Em.out.println (new String (buffer));}} catch (Unknownhostexception e) {//TODO auto-generated catch block E.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch block E.P Rintstacktrace ();} Finally {try {socket.close (); Inputstream.close ();} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();}}}
Run server-side first, print the results:

==>> Accepting
Then run the client and print the results:

==>> Hello Client,this is a message from server

Example two: Socket communication based on TCP/IP protocol one-to-many:

You only need to cycle the server segment with one thread

Package Z_test_socket_demo;import Java.io.ioexception;import Java.io.outputstream;import java.net.ServerSocket; Import Java.net.socket;public class Testserversocket {public static void main (string[] args) {//TODO auto-generated method stub new Thread ( New Serverthread ()). Start ();}  private static class Serverthread implements Runnable {@Overridepublic void Run () {//TODO auto-generated method stub int i = 1;while (true) {ServerSocket serversocket = null; Socket socket = Null;outputstream OutputStream = null;try {serversocket = new ServerSocket (8888);//Specify Listening port System.out.prin TLN ("==>> accepting client" + i++); socket = Serversocket.accept (); Listen for client's request, method block, request succeeds, return socket object outputstream = Socket.getoutputstream (); Gets the output stream string string = "==>> Hello client" + i+++ ", this is a message from server"; Send something to the client. byte[] buffer = string.getbytes (); outputstream.write (buffer); Outputstream.flush ();} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();} finally {try {serversocket.close (); Socket.close (); O UtputstrEam.close ();} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();}}}}}
Run the server segment and print the results:

==>> Accepting CLIENT1

To run the client, the client prints the result:

==>> Hello Client1,this is a message from server

Run the client again, and the client prints the result:

==>> Hello Client2,this is a message from server

Equivalent to two different client requests to connect to a server


Understand the socket communication based on TCP/IP protocol, socket communication based on other protocols should be able to understand quickly.


Java:socket Communication

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.