终于建了一个自己个人小站:https://huangtianyu.gitee.io,以后优先更新小站博客,欢迎进站,O(∩_∩)O~~
先上代码,可以先把代码下下来,对着代码看本文。代码地址是:https://github.com/huangtianyu/SocketDemo,代码记得点击star哦~
总有些想尝试一些底层的人,之前做过socket开发,总是想能不能用socket实现手机和服务器直接通信。尝试了下,还是不难的。毕竟都是用Java写的,无论是Android端还是服务器端,都是对Socket的使用。下面给出具体代码。
先看服务器端代码:
Server.java
package com.scu; 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 { public void run() { try { // 创建ServerSocket ServerSocket serverSocket = new ServerSocket(6868); while (true) { // 接受客户端请求 Socket client = serverSocket.accept(); if (client == null) { continue; } System.out.println("客户端来了"); try { // 接收客户端消息 BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String str = in.readLine(); System.out.println("收到:" + str); // 向服务器发送消息 PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true); out.println("服务器收到了"); // 关闭流 out.close(); in.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { // 关闭 client.close(); System.out.println("close"); } } } catch (Exception e) { System.out.println(e.getMessage()); } } // main函数,开启服务器,这就是一个普通的Java类,可以放到命令行里面执行的 public static void main(String a[]) { Thread desktopServerThread = new Thread(new Server()); desktopServerThread.start(); } }
上面是普通的Java类,可以直接放到命令行里面编译然后执行(javac Server.java,然后java Server即可)。首先初始化一个ServerSocket,利用一个while循环,不断循环接收客户端请求。注意ServerSocket类的accept函数将会阻塞线程的运行,当没有客户端发来请求时,服务器将会停在accept方法处,直到有客户端发送请求。
下面看看Android端代码:
package com.zqc.socketdemo; 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; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; public class MainActivity extends Activity { private final String DEBUG_TAG = "hty"; private TextView mTextView = null; private EditText mEditText = null; private Button mButton = null; Socket socket = null; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = (Button) findViewById(R.id.Button01); mTextView = (TextView) findViewById(R.id.TextView01); mEditText = (EditText) findViewById(R.id.EditText01); mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread(){ @Override public void run() { String message = mEditText.getText().toString(); try { //创建Socket socket = new Socket("10.18.73.62", 6868);//第一个参数是ip地址,第二个是端口号 //向服务器发送消息 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); out.println(message); //接收来自服务器的消息 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg = new String(in.readLine().getBytes(),"UTF-8"); if (msg != null) { mTextView.setText(msg); } else { mTextView.setText("数据错误!"); } //关闭流 out.close(); br.close(); } catch (Exception e) { Log.e(DEBUG_TAG, e.toString()); } finally { //关闭Socket try { if (socket != null) { socket.close(); } } catch (Exception e) { } } } }.start(); } }); } }在Android端首先初始化一个Socket,然后获取该Socket的输出流,在调用out.println的时候框架会自动进行socket请求并发送数据。可以通过socket.getInputStream()获取Socket的输入流,从而可以接收服务器的输出。
具体代码可以参考github:https://github.com/huangtianyu/SocketDemo