一直以来对Android socket通信都很模糊,今天终于研究了一个网上的例子,自己又修改了下,算是对Android socket通信有点了解了。
下面是具体的代码,说明都在注释中了。需要注意的是,只有客户端发送了信息给服务器后,服务器才能响应客户端的输入,然后返回信息给客户端,这是客户端才能读取服务器返回的信息。如果客户端和服务器都处于等待对方的信息,那样就会造成阻塞,导致ANR了。
1.服务器端代码,就是一个java程序,与android无关,运行于服务器上,即PC机上。
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- * 测试Android客户端与PC服务器通过socket进行交互
- * 服务器端:接收客户端的信息并回送给客户
- * @author Ameyume
- *
- */
- public class Server implements Runnable {
- public static final String SERVERIP = "192.168.1.100";
- public static final int SERVERPORT = 51706;
- public void run() {
- try {
- System.out.println("S: Connecting...");
- ServerSocket serverSocket = new ServerSocket(SERVERPORT);
- while (true) {
- // 等待接受客户端请求
- Socket client = serverSocket.accept();
- System.out.println("S: Receiving...");
- try {
- // 接受客户端信息
- BufferedReader in = new BufferedReader(
- new InputStreamReader(client.getInputStream()));
- // 发送给客户端的消息
- PrintWriter out = new PrintWriter(new BufferedWriter(
- new OutputStreamWriter(client.getOutputStream())),true);
- System.out.println("S: 111111");
- String str = in.readLine(); // 读取客户端的信息
- System.out.println("S: 222222");
- if (str != null ) {
- // 设置返回信息,把从客户端接收的信息再返回给客户端
- out.println("You sent to server message is:" + str);
- out.flush();
- // 把客户端发送的信息保存到文件中
- File file = new File ("C://android.txt");
- FileOutputStream fops = new FileOutputStream(file);
- byte [] b = str.getBytes();
- for ( int i = 0 ; i < b.length; i++ )
- {
- fops.write(b[i]);
- }
- System.out.println("S: Received: ‘" + str + "‘");
- } else {
- System.out.println("Not receiver anything from client!");
- }
- } catch (Exception e) {
- System.out.println("S: Error 1");
- e.printStackTrace();
- } finally {
- client.close();
- System.out.println("S: Done.");
- }
- }
- } catch (Exception e) {
- System.out.println("S: Error 2");
- e.printStackTrace();
- }
- }
- public static void main(String [] args ) {
- Thread desktopServerThread = new Thread(new Server());
- desktopServerThread.start();
- }
- }
2.客户端程序,运行在手机或者模拟器上。
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.net.InetAddress;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- /**
- * 测试Android客户端与PC服务器通过socket进行交互
- * 客户端:把用户输入的信息发送给服务器
- * @author Ameyume
- *
- */
- public class Socket_Android extends Activity {
- private static final String TAG = "Socket_Android";
- private EditText mEditText = null;
- private TextView tx1 = null;
- private Button mButton = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mButton = (Button)findViewById(R.id.Button01);
- mEditText = (EditText)findViewById(R.id.etSendMsg);
- tx1 = (TextView)findViewById(R.id.tx);
- mButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- setTitle("测试Socket连接");
- Socket socket = null;
- try {
- /* 指定Server的IP地址,此地址为局域网地址,如果是使用WIFI上网,则为PC机的WIFI IP地址
- * 在ipconfig查看到的IP地址如下:
- * Ethernet adapter 无线网络连接:
- * Connection-specific DNS Suffix . : IP Address. . . . . . . . . . . . : 192.168.1.100
- */
- InetAddress serverAddr = InetAddress.getByName("192.168.1.100");// TCPServer.SERVERIP
- Log.d("TCP", "C: Connecting...");
- // 应用Server的IP和端口建立Socket对象
- socket = new Socket(serverAddr, 51706);
- String message = "---Test_Socket_Android---";
- Log.d("TCP", "C: Sending: ‘" + message + "‘");
- // 将信息通过这个对象来发送给Server
- PrintWriter out = new PrintWriter(new BufferedWriter(
- new OutputStreamWriter(socket.getOutputStream())),
- true);
- // 把用户输入的内容发送给server
- String toServer = mEditText.getText().toString();
- Log.d(TAG, "To server:‘" + toServer + "‘");
- out.println(toServer);
- out.flush();
- // 接收服务器信息
- BufferedReader in = new BufferedReader(
- new InputStreamReader(socket.getInputStream()));
- // 得到服务器信息
- String msg = in.readLine();
- Log.d(TAG, "From server:‘" + msg + "‘");
- // 在页面上进行显示
- tx1.setText(msg);
- } catch(UnknownHostException e) {
- Log.e(TAG, "192.168.1.100 is unkown server!");
- } catch(Exception e) {
- e.printStackTrace();
- } finally {
- try {
- socket.close();
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
- });
- }
- }
3.在客户端AndroidManifest.xml文件增加访问互联网的权限
- <uses-permission android:name="android.permission.INTERNET" />
4.运行效果:
服务器接的log输出:
S: Receiving...
S: 111111
S: 222222
S: Received: ‘hello‘
S:
Done.
本文参考自:Android通过socket连接服务器(PC)