Fully Understand socket programming

Source: Internet
Author: User

Step 1: fully understand socket

1. What is socket?

The so-called socket is also called "socket". It is used to describe the IP address and port and is a communication chain handle. Applications usually send requests to or respond to network requests through "Sockets.

Taking J2SDK-1.3 as an example, the socket and serversocket class libraries are located in the java.net package. Serversocket is used on the server side. socket is used to establish a network connection. When the connection is successful, a socket instance is generated at both ends of the application to complete the required session. For a network connection, sockets are equal and there is no difference, not because of different levels on the server side or on the client side. Both socket and serversocket work through the socketimpl class and its subclass.

Important socket APIs:

Java.net. Socket inherited from Java. Lang. Object, there are eight constructors, the method is not much, the following describes the use of the most frequent three methods, other methods you can see the JDK-1.3 documentation.

The. Accept method is used to generate "blocking" until a connection is received and a client's socket object instance is returned. "Blocking" is a term that enables the program to run temporarily "Stay" in this place until a session is generated and then the program continues. Generally, "blocking" is produced by a loop.

The. getinputstream method obtains the network connection input and returns an iutputstream object instance ,.

The other end connected by the. getoutputstream method will get the input and return an outputstream object instance.

Note: The getinputstream and getoutputstream methods both generate an ioexception, which must be captured because the returned stream objects are usually used by another stream object.

2. How to develop a server-client model program

Development Principles:

Server, using ServerSocket to listen to the specified port, the port can be specified at Will (because the port below 1024 is usually a reserved port, it cannot be used in some operating systems, therefore, we recommend that you use a port greater than 1024). Wait for the client connection request. After the client connects, the session is generated. After the session is completed, the connection is closed.

The client uses a Socket to send a connection request to a port of a server on the network. Once the connection is successful, the session is opened. After the session is complete, the Socket is closed. The client does not need to specify the opened port. Generally, a temporary and dynamic port of over 1024 is allocated.

{Create server}

 

Import java.net .*;
Import java. io .*;

Public class Server
{
Private ServerSocket ss;
Private Socket socket;
Private BufferedReader in;
Private PrintWriter out;

Public Server ()
{
Try
{
Ss = new ServerSocket (10000 );

While (true)
{
Socket = ss. accept ();
In = new BufferedReader (new InputStreamReader (socket. getInputStream ()));
Out = new PrintWriter (socket. getOutputStream (), true );

String line = in. readLine ();
Out. println ("you input is:" + line );
Out. close ();
In. close ();
Socket. close ();
}
Ss. close ();
}
Catch (IOException e)
{}
}

Public static void main (String [] args)
{
New Server ();
}
}

This program creates a server that listens to port 10000 and waits for the user to connect. After the connection is established, a piece of information is returned to the client and the session ends. This program can only accept one client connection at a time.

{Create a client}

Import java. io .*;
Import java.net .*;

Public class Client
{
Socket socket;
BufferedReader in;
PrintWriter out;

Public Client ()
{
Try
{
Socket = new Socket ("xxx. XXXXX", 10000 );
In = new BufferedReader (new InputStreamReader (socket. getInputStream ()));
Out = new PrintWriter (socket. getOutputStream (), true );
BufferedReader line = new BufferedReader (new InputStreamReader (System. in ));

Out. println (line. readLine ());
Line. close ();
Out. close ();
In. close ();
Socket. close ();
}
Catch (IOException e)
{}
}

Public static void main (String [] args)
{
New Client ();
}
}

The client connects to the server with the address xxx. xxx. port 10000, input a line of information from the keyboard, send it to the server, then accept the server's return information, and finally end the session.

Step 2 multiple clients connect simultaneously

In the actual network environment, only one user service at a time is not feasible. In addition to processing user input, an excellent network service program must be able to respond to connection requests from multiple clients at the same time. In java, it is very easy to implement the above features.

Design principle:

The main program listens to a port and waits for the client to access it. At the same time, it constructs a Thread class to take over the session. When a socket session is generated, the session is handed over to the thread for processing, and the main program continues to listen. Using the Thread class or runnable interface is a good solution.

{Message sharing}

Import java. Io .*;
Import java.net .*;

Public class Server extends serversocket
{
Private Static final int server_port = 10000;

Public server () throws ioexception
{
Super (server_port );

Try
{
While (true)
{
Socket socket = accept ();
New createserverthread (socket );
}
}
Catch (ioexception E)
{}
Finally
{
Close ();
}
}
// --- Createserverthread
Class createserverthread extends thread
{
Private Socket client;
Private BufferedReader in;
Private PrintWriter out;

Public CreateServerThread (Socket s) throws IOException
{
Client = s;

In = new BufferedReader (new InputStreamReader (client. getInputStream (), "GB2312 "));
Out = new PrintWriter (client. getOutputStream (), true );
Out. println ("--- Welcome ---");
Start ();
}

Public void run ()
{
Try
{
String line = in. readLine ();

While (! Line. equals ("bye "))
{
String msg = createMessage (line );
Out. println (msg );
Line = in. readLine ();
}
Out. println ("--- See you, bye! ---");
Client. close ();
}
Catch (ioexception E)
{}
}

Private string createmessage (string line)
{
XXXXXXXXX;
}
}

Public static void main (string [] ARGs) throws ioexception
{
New server ();
}
}

This program listens to port 10000 and passes the access to the createserverthread thread for running. The createserverthread thread accepts the input and returns the input to the customer until the customer inputs "bye" and the thread ends. We can process the input in the createmessage method, generate the result, and then return the result to the customer.

Step 3: Achieve Information Sharing: real-time communication on the socket

One of the greatness of the network is information sharing. The server can actively broadcast messages to all clients, and the client can also publish messages to other clients. The following describes how to develop a program that can transmit messages in real time.

Design principle:

The server accepts client connection requests and starts a thread to process the connection. The thread keeps reading client input and adds the input to the queue for processing. Add the thread to the queue when the thread starts, so that it can be located and retrieved as needed.

{Source code}

Import java. Io .*;
Import java.net .*;
Import java. util .*;
Import java. Lang .*;

Public class Server extends serversocket
{
Private Static arraylist user_list = new arraylist ();
Private Static arraylist threader = new arraylist ();
Private Static consumer list message_array = new consumer list ();
Private Static int thread_counter = 0;
Private Static Boolean isclear = true;
Protected static final int server_port = 10000;
Protected fileoutputstream LOG_FILE = new fileoutputstream ("D:/connect. log", true );

Public server () throws filenotfoundexception, ioexception
{
Super (server_port );
New broadcast ();

// Append connection log
Calendar now = calendar. getinstance ();
String STR = "[" + now. gettime (). tostring () + "] accepted a connection/015/012 ";
Byte [] tmp = str. getBytes ();
LOG_FILE.write (tmp );

Try
{
While (true)
{
Socket socket = accept ();
New CreateServerThread (socket );
}
}
Finally
{
Close ();
}
}

Public static void main (String [] args) throws IOException
{
New Server ();
}

// --- Broadcast
Class Broadcast extends Thread
{
Public Broadcast ()
{
Start ();
}

Public void run ()
{
While (true)
{
If (! IsClear)
{
String tmp = (String) Message_Array.getFirst ();

For (int I = 0; I <Threader. size (); I ++)
{
CreateServerThread client = (CreateServerThread) Threader. get (I );
Client. sendMessage (tmp );
}

Message_Array.removeFirst ();
IsClear = Message_Array.size ()> 0? False: true;
}
}
}
}

// --- CreateServerThread
Class CreateServerThread extends Thread
{
Private Socket client;
Private BufferedReader in;
Private PrintWriter out;
Private String Username;

Public CreateServerThread (Socket s) throws IOException
{
Client = s;
In = new BufferedReader (new InputStreamReader (client. getInputStream ()));
Out = new PrintWriter (client. getOutputStream (), true );
Out. println ("--- Welcome to this chatroom ---");
Out. println ("input your nickname :");
Start ();
}

Public void sendmessage (string MSG)
{
Out. println (MSG );
}

Public void run ()
{
Try
{
Int flag = 0;
Thread_counter ++;
String line = in. Readline ();

While (! Line. Equals ("bye "))
{
If (line. Equals ("L "))
{
Out. println (listonlineusers ());
Line = in. Readline ();
Continue;
}

If (flag ++ = 0)
{
Username = line;
User_list.add (username );
Out. println (listonlineusers ());
Threader. Add (this );
PushMessage ("[<" + Username + "come on in>]");
}
Else
{
PushMessage ("<" + Username + ">" + line );
}

Line = in. readLine ();
}

Out. println ("--- See you, bye! ---");
Client. close ();
}
Catch (IOException e)
{}
Finally
{
Try
{
Client. close ();
}
Catch (IOException e)
{}

Thread_Counter --;
Threader. remove (this );
User_List.remove (Username );
PushMessage ("[<" + Username + "left>]");
}
}

Private String listOnlineUsers ()
{
String s = "-+-Online list-+-/015/012 ";

For (int I = 0; I <User_List.size (); I ++)
{
S + = "[" + User_List.get (I) + "]/015/012 ";
}

S + = "-+ ------------------- + -";
Return s;
}

Private void pushMessage (String msg)
{
Message_Array.addLast (msg );
IsClear = false;
}
}
}

 

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.