/*************************************** **************************************** *************
* Author: conowen @ Dazhong
* E-mail: conowen@hotmail.com
* Http://blog.csdn.net/conowen
* Note: This article is original and only used for learning and communication. For more information, indicate the author and its source.
**************************************** **************************************** ************/
1. Socket Introduction
Generally, a socket is also called a socket ". Literally, the Chinese meaning of socket is "socket ". For example, a server may provide many services. Each Service corresponds to a socket. (You can also say that each socket is a socket. If the customer needs this service, plug the plug to the corresponding socket) and the customer's "plug" is also a socket. The server needs to communicate with the client, both of which need to instantiate a socket.
Java provides two classes in the java.net package: serversocket and socket. The former is used to instantiate the socket of the server, and the latter is used to instantiate the socket of the client, that is, the socket of the server and the client is different.
2. Brief description of socket communication process
Generally, we only need to construct the socket of the client to communicate with the target server. However, to facilitate the demonstration, let's assume that the server is also our own architecture.
2.1 First, construct the client socket
There are several socket methods used to construct the client. The parameters usually point to the IP address of the target server, the port number of the target server, and the host name of the target server.
For example: // Note: 0 ~ Port 1023 is retained by the system. The user-defined port number must be greater than 1023.
Socket Client = new socket ("192.168.1.23", 2012); // The first parameter is the IP address of the target server. 2012 is the port number of the target server.
Proxy is the proxy server address, dstaddress is the target server IP address, dstport is the port number of the target server (because each service on the server is bound to a port), and dstname is the host name of the target server.
2.2. Then construct the server's serversocket
The following types of sockets are used to construct a server:
For example:
Serversocket socketserver = new serversocket (2012); // 2012 indicates the port number of the server to listen
After constructing the serversocket, you need to call the serversocket. Accept () method to wait for the client request (because the socket is bound to the port, so you know the client request ).
The accept () method returns the socket instance of the Client requesting this service. Then, the transmitted information is operated through the method of the returned socket instance. For the operation method, see 2.3 ~
Public
Socket accept () (blocking function, that is, after the method is called, it will wait for the client's request until a client requests a connection and returns the socket instance) since: API Level 1
Waits for an incoming request and blocks until the connection is opened. This method returns a socket object representing the just opened connection.
Returns
- The connection representing socket.
Throws
Ioexception |
If an error occurs while accepting a new connection. |
2.3 first, understand that socket communication uses an input/output stream.
Socket provides the getinputstream () and getoutputstream () methods to obtain and send Io streams. Note: serversocket instances do not have these two methods. The two methods can be used to obtain the socket object of the client by calling the serversocket. Accept () method on the server.
The getinputstream () and getoutputstream () Methods return inputstream and outputstream class objects respectively.
2.4. Reclaim Resources
Although the system automatically recycles resources, we recommend that you manually Recycle resources.
When each socket is enabled, the system resources are used. When the socket object is completed, it should be closed. (Both the socket on the server and the socket on the client must be closed)
Before connecting to the socket, make sure that all socket input and output streams are closed.
outstream.close();intstream.close();clientsocket.close();
3. Simple Chat demo
This demo includes servers and clients. The server is compiled and run on the "command prompt interface" of the computer, and the client compilation is run on the android simulator. Then, the android simulator chats and communicates with the server program on the computer. (Note: The demo is relatively simple, and only one sending operation can be performed. If multiple sending operations are performed, blocking will occur. You can use multiple threads to solve the problem. For more information, see the previous blog post, user-Defined code)
In addition, there will be garbled Chinese characters for such communication. Solution: Coding and transcoding. write a blog post for details in a few days.
Server
Client
3.1 compile the server source code in the execution method:
Create a Java file and use the command prompt interface to jump to the directory of the Java file. Run the following command:
javac SocketSer.java
Run the following command after compilation: // socketserver is the name of the class on the server. You can customize it.
java SocketServer
3.2. The source code of the server is as follows:
/* Author: conowen * Date: 2012.3.5 */import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. serversocket; import java.net. socket; public class socketserver {public static void main (string [] ARGs) throws ioexception {serversocket socketserver = new serversocket (8025); // create a serversocket and set the port number to 8025system. out. println ("START session ...... "); Socket socketclient = socketserver. accept (); // obtain the client socket object // obtain an input object from socketclient to receive data from the client bufferedreader socketinput = new bufferedreader (New inputstreamreader (socketclient. getinputstream (); // obtain an output object to return server information to the client printwriter socketoutput = new printwriter (socketclient. getoutputstream (), true); While (true) {string temp = socketinput. readline (); // read the information of the input object system. out. print ("client:"); syst Em. Out. println (temp); socketoutput. println ("server: I get it! "); // Return the information to the client }}}
3.3 client source code
The client is an android Project
Compile with eclipse
The Code is as follows:
/* Author: conowen * Date: 2012.3.5 */package COM. conowen. mysocket; import Java. io. bufferedreader; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. socket; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; public class mysocketactivity extends activity {edittext display; edittext input; static final int Port = 8025; // port number static final string ipadd = "192.168.31.164 "; // server IP Address/** called when the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); button sendbt = (button) findviewbyid (R. id. BT); // send the button display = (edittext) findviewbyid (R. id. ET1); // used to display the information returned by the server input = (edittext) findviewbyid (R. id. et2); // used to obtain the input information of the client sendbt. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubtry {string socketstr = input. gettext (). tostring (); // obtain the edittext content Socket Client = new socket (ipadd, Port); // create a socket // obtain an output object from the socket, in order to send the data entered by edittext to the client printwriter socketoutput = new printwriter (client. getoutputstream (), true); socketoutput. println (socketstr); // send it to the socketoutput server. flush (); // clear the cache // obtain an input object from the client's socket to receive information from the server bufferedreader socketinput = new bufferedreader (New inputstreamreader (client. getinputstream (); string textviewstr = socketinput. readline (); // read the content of the input object and display it. settext (textviewstr); // display content} catch (exception e) {// todo: handle exception }}});}}
Remember to add network permissions to the androidmanifest. xml file.
<uses-permission android:name="android.permission.INTERNET"/>