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 for Servers
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
The socket layer is equal and there is no difference. It does not generate different levels on the server side or on the client side. Both socket and serversocket work through
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.
Connect multiple customers at the same time:
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.
Now implement server-side programming: (TCP-based)
Myserver. Java
---------------------------------------------------
Package server;
Import java. Io. inputstream;
Import java. Io. outputstream;
Import java.net. serversocket;
Import java.net. Socket;
Import java. util. date;
// This simple socket server mainly refers to the sentence Hello XXX, which is implemented using multiple threads.
Public class myserver extends thread {
Private socket S;
Public static void main (string [] ARGs ){
Myserver. Server (); // main entry. The server service is activated once the machine is run.
}
Public myserver (socket s ){
This. S = s;
}
Public void run (){
Try {
Outputstream OS = S. getoutputstream ();
Inputstream is = S. getinputstream ();
Byte [] Bu = new byte [20];
Int Len = is. Read (BU); // read the message from the client
String username = new string (Bu, 0, Len );
Date d = new date ();
System. Out. println (username + "is coming here at" + D. tolocalestring (); // logs written on the server console are displayed.
String welcome = "hello," + username + "! ";
// System. Out. println (welcome );
OS. Write (welcome. getbytes (); // The welcome message returned to the client.
OS. Close ();
Is. Close ();
S. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}
Public static void server (){
Try {
Serversocket Ss = new serversocket (9527); // server socket, port 9527
While (true ){
Socket S = ss. Accept ();
New myserver (s). Start (); // The user runs a thread as soon as it comes in.
}
} Catch (exception e ){
E. printstacktrace ();
}
}
}
Client programming:
Myclient. Java
---------------------------------
Package client;
Import java. Io .*;
Import java.net .*;
Public class myclient {
Public static void main (string [] ARGs ){
// Force the user to enter the user name and call the client (STR) method.
String STR = "";
Try {
While (Str. Length () <1 ){
System. Out. println ("enter your name ");
STR = new datainputstream (New bufferedinputstream (system. In ))
. Readline ();
}
} Catch (exception e ){
E. printstacktrace ();
}
Myclient. Client (STR );
}
Public static void client (string username ){
Try {
Socket S = new socket (inetaddress. getbyname ("127.0.0.1"), 9527); // the IP address and port number of the socket
Outputstream OS = S. getoutputstream ();
Inputstream is = S. getinputstream ();
Byte [] Name = username. getbytes ("ISO-8859-1"); // This is for Chinese garbled Problem
OS. Write (name); // send a message to the server
Byte [] serversay = new byte [100];
Int Len = is. Read (serversay); // receives server messages
System. Out. println (new string (serversay, 0, Len); // The console displays the information returned by the server.
Is. Close ();
OS. Close ();
S. Close (); // remember to close these inputs, output streams, and sockets.
} Catch (exception e ){
E. printstacktrace ();
}
}
}