Android网络编程socket

xiaoxiao2021-02-28  43

参考博文:https://www.cnblogs.com/llguanli/p/6839410.html

更多内容请点击Socket是用攻略

为了便于操作,我们客户端和服务端都放在手机上,等于客户访问的服务端就是设备本身的某一个端口。

下面是服务端的代码:

/** * Created by Administrator on 2018/5/18.10:47 * 服务端socket */ public class ServerSocket { public static final String TAG = "ServerSocket"; public ServerSocket() { AsyncTask.execute(new Runnable() { @Override public void run() { startServer(); } }); } private void startServer() { Socket socket = null; InputStream inputStream = null; try { //创建serversocket java.net.ServerSocket serverSocket = new java.net.ServerSocket(9999); socket = serverSocket.accept();//返回客户端socket inputStream = socket.getInputStream();//获取输入流 byte[] bytes = new byte[1024]; int len= -1; if(((len = inputStream.read(bytes)) != -1)){//从客户端传输过来的数据 Log.d(TAG, "startServer: " + new String(bytes,0,len)); } } catch (IOException e) { e.printStackTrace(); }finally { if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } inputStream = null; } if(socket != null){ try { socket.close(); socket = null; } catch (IOException e) { e.printStackTrace(); } } } } }

客户端代码:

/** * Created by Administrator on 2018/5/18.10:47 */ public class ClientSocket { public ClientSocket() { AsyncTask.execute(new Runnable() { @Override public void run() { startClient(); } }); } private void startClient() { Socket socket = null; OutputStream outputStream = null; try { //创建socket客户端,第一个参数主机名(127.0.0.1就是设备本身), // 第二个参数端口号,这需要和服务端的端口号一致 socket = new Socket("127.0.0.1",9999); outputStream = socket.getOutputStream();//获取输入流,此输出流的终端是服务器端 outputStream.write("这是来自客户端的请求".getBytes());//写入的数据 } catch (IOException e) { e.printStackTrace(); }finally { if(outputStream != null){ try { outputStream.close(); outputStream = null; } catch (IOException e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); socket = null; } catch (IOException e) { e.printStackTrace(); } } } }
转载请注明原文地址: https://www.6miu.com/read-2620493.html

最新回复(0)