Android Study Notes (30)-simple use of network communication socket

Source: Internet
Author: User

About socket, Baidu encyclopedia said this:

What is socket

The so-called socket is also known as "socket". An application usually sends a request to or responds to a network request through "socket. 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.

Important socket APIs

Important Socket API: Java. net. socket inherits 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. 1. 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. 2. The getinputstream method obtains the network connection input and returns an inputstream object instance. 3. The other end connected by the getoutputstream method will get the input and return an outputstream object instance. Note: Both the getinputstream and getoutputstream methods can generate an ioexception, which must be captured because the returned stream objects are usually used by another stream object.

Socket connection process

Based on the connection start method and the target to which the local socket is to be connected, the connection process between sockets can be divided into three steps: server listening, client request, and connection confirmation.

Server listener: A server socket does not locate a specific client socket, but is waiting for a connection. It monitors the network in real time.

Client request: a connection request is initiated by the client socket. The target is the socket on the server. Therefore, the client socket must first describe the socket of the server to be connected, point out the address and port number of the socket on the server, and then submit a connection request to the socket on the server.

Connection Confirmation: when the server socket monitors or receives a connection request from the client socket, it responds to the request from the client socket and creates a new thread, send the description of the server socket to the client. Once the client confirms the description, the connection is established. The server socket continues to be in the listening status, and continues to receive connection requests from other client sockets.

The following uses a server and client as an example to describe how to use socket:

1. server side:

Procedure:

1.1 instantiate a serversocket through a specified port

1.2. Calling the serversocket accept () causes blocking during the waiting period

1.3 obtain the stream of the underlying socket for read/write operations

1.4 encapsulate the database into a stream

1.5 perform socket read/write

1.6 Close the opened stream and Socket

The server code is as follows:

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;public class Server implements Runnable {@Overridepublic void run() {// TODO Auto-generated method stubtry {ServerSocket serverSocket = new ServerSocket(54323);while (true) {Socket client = serverSocket.accept();try {BufferedReader read = new BufferedReader(new InputStreamReader(client.getInputStream()));String str = read.readLine();System.out.println("read-->" + str);PrintWriter write = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);write.println("server message");read.close();write.close();} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e.getMessage());e.printStackTrace();}finally{client.close();}}} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e.getMessage());}}public static void  main(String a[]) {Thread ServerThread = new Thread(new Server());ServerThread.start();}}

2. Client

Procedure:

2.1 instantiate a socket through IP addresses and ports and request to connect to the server

2.2 obtain the stream on the socket for read/write

2.3 Package data streams into bufferedreader/printwriter instances

2.4 perform socket read/write operations

2.5 close the opened socket

The client code is as follows (the XML file is no longer provided ):

package com.ideal.socket;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.InputStreamReader;import java.io.OutputStreamWriter;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;import android.widget.TextView;public class Net_SocketClientActivity extends Activity {private TextView mTextView = null;private EditText mEditText = null;private Button mButton = null;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mButton = (Button) findViewById(R.id.Button01);mTextView = (TextView) findViewById(R.id.TextView01);mEditText = (EditText) findViewById(R.id.EditText01);mButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) { // TODO Auto-generated method stubSocket socket = null;String message = mEditText.getText().toString() + "\r\n";try {socket = new Socket("172.31.100.50", 54323);PrintWriter write = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);write.println(message);BufferedReader read = new BufferedReader(new InputStreamReader(socket.getInputStream()));String msg = read.readLine();if(msg!=null){mTextView.setText(msg);}else {mTextView.setText("error");}write.close();read.close();socket.close();} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e.getMessage());}}});}}

3. For the client and server, note the following:

3.1 server and client can be used in the same LAN

3.2,

socket = new Socket("172.31.100.50", 54323);

The above IP address is not an Internet IP address. I use the following IPv4 address:

In addition, port problems may occur. If your port (54323 above) is occupied, the following situation may occur:

Solution:

1. Change the server port number;

2. Disable the process that occupies the current port.

The second method is described below.

1. First enter the command line
Check whether the port is occupied

Run the following command:
Netstat-ano

2. Check that the PID is
54323 of processes

Run tasklist | findstr.
"54323"

Then, you can exit the process directly or close the process in the task manager.

4. Check the running result:

Client:

Server:

View the console in eclipse


CMD command window view

Related Article

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.