Three steps learn Java Socket programming

xiaoxiao2021-03-06  47

What is Socket

The so-called socket is also also referred to as "socket", used to describe the IP address and port, a handle of a communication chain. Applications typically send requests or response network requests to the network via "socket".

Take J2SDK-1.3 as an example, Socket and Serversocket class libraries are located in the Java.net package. ServerSocket is used for server-side, and Socket is used when it is created. When the connection is successful, both ends of the application generate a Socket instance, operate this instance, and complete the session you need. For a network connection, the socket is equal and there is no difference, not because of the different levels of different levels in the server or on the client. Whether it is Socket or Serversocket, their work is done through the SocketImpl class and their subclasses.

Important Socket API:

Java.net.socket inherits in java.Lang.Object, there are eight constructors, and there are not many methods. Here is three ways to use the most frequent methods, and other methods can see JDK-1.3 documentation.

The ACCEPT method is used to generate "blocked" until a connection is accepted, and a client's Socket object instance is returned. "Block" is a term that makes the program to run temporary "stay" in this place until a session is generated, and then the program continues; usually "blocked" is generated by the loop.

The GetInputStream method obtains a network connection input while returning an IUTPUTSTREAM object instance.

. GetputStream method The other end of the connection will be entered while returning an OutputStream object instance.

Note: The GetInputStream and getOutputStream methods generate an IOException, which must be captured because they return the stream objects, usually by another stream object.

2. How to develop a server for a Server-Client model

Development principle:

Server, use the ServerSocket to listen to the specified port, the port can be specified (Since the port 1024 is usually belonging to the reserved port, it is not possible to use in some operating systems, so it is recommended to use a port greater than 1024, waiting for the customer connection request, customer connection After the session; after the session is completed, turn it off.

The client, uses socket to send a connection request for a port of a server on a server on the network, once the connection is successful, open the session; after the session is complete, turn off the Socket. The client does not need to specify the port, usually temporarily, dynamically assigned a 1024 port.

{Establish 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 (ooException e) {}}} PUBLIC Static void main (String [] args) {new server ();}} This program has established a server that has been listening to 10000 ports, waiting for the user to connect. Return to a message to the client after establishing a connection, and then end the session. This program can only accept one customer connection at a time.

{Establish client}

Import java.io. *; import java.net. *; public class client {socket socket; buffredreader in; printwriter out; public client () {try {socket = new socket ("xxx.xxx.xxx.xxx", 1000 ); 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 (ooexception e) {}} public static void main (String [] args ) {new client ();}}

This client is connected to the address of XXX.xxx.xxx.xxx, the port is 1000, and enter a line of line information from the keyboard, send it to the server, and then accepts the server's return information, and finally ends the session.

In the second step, multiple customers are connected to the actual network environment at the same time, and only one user service is not feasible. A excellent network service program must deal with the user's input information, must also be able to simultaneously respond to the connection request of multiple clients. In Java, it is very easy to achieve the above features. Design principle: Main program listening to one end, waiting for customer access; constructing a thread class, ready to take over the session. When an Socket session is generated, this session is given to thread processing, and then the main program continues to listen. It is a good way to use the Thread class or Runnable interface. {Implement 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 ();}} // --- CreateServerThreadclass 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 oews oews Ception {new server ();}} This program listens to 10000 port and handles the access to the CreateSerVerthread thread. The CreateServertHread thread accepts input and responds to customers until the client enters "BYE" and the thread ends. In the createMessage method, we can process the input and generate results, and then return the result to the customer.

Step 3 Implementation Information Sharing: One of the greatness of real-time communication networks on Socket is also information sharing, and Server can actively broadcast messages to all Client, while Client can also post messages to other clients. Let's take a look at how to develop a program that can deliver messages in real time. Design principle: Server-side accepts client connection requests, while starting a thread handling this connection, the thread is constantly reading the client input, and then the input is added to the queue, waiting for processing. Add the thread to the queue while the thread is started to locate and take out when 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 LinkedList Message_Array = new LinkedList (); 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 logCalendar 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 ooException {new server ();} // --- Broadcast () Broadcast Extends thread {public Broadcast () {star T ();} public void Run () {while {if (! isclear) {string tmp = (string) message_array.getfirst (); for (int i = 0; i 0 false: true;}}}} // -? - CreateServerThreadclass 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.getOutstream (), true); Out.println ("--- Welcome to this chat"); 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) {user_list.add (username) Out.println (ListonLineUsers (); threader.add (this); pushmessage ("[<" username "come on in in>]");} else {PushMessage ("<" username "> Line);} line = in.readline ();} out.println ("--- See you, bye! ---"); client.close ();} catch (ooException 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

转载请注明原文地址:https://www.9cbs.com/read-115925.html

New Post(0)