Learn Java socket programming in three steps

Source: Internet
Author: User
Learn Java socket programming in three steps

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;
}
}
}

This is the screen after multiple users log on and enter information after the program runs. Real-time information broadcasting is realized. You can enter "L" to list online personnel tables.

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.