socket通信需要有一个服务器和客户端,可以把同一个APP作为服务器跟客户端,也可以分开成两个APP。
先上个图:
这里以一个APP作为服务器跟客户端为示例
1、添加网络访问权限
<uses-permission androID:name="androID.permission.INTERNET" />
2、写服务器,在APP上启动
import java.io.DatainputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.InetAddress;import java.net.ServerSocket;import java.net.socket;public class Server { ServerSocket serverSocket = null; public final int port = 9998; private int i = 0; public Server(){ //输出服务器的IP地址 try { InetAddress addr = InetAddress.getLocalHost(); System.out.println("local host:"+addr); serverSocket = new ServerSocket(port); System.out.println("0k"); } catch (IOException e) { // Todo auto-generated catch block e.printstacktrace(); } } public voID startService(){ try { Socket socket = null; System.out.println("waiting..."); //等待连接,每建立一个连接,就新建一个线程 while(true){ socket = serverSocket.accept();//等待一个客户端的连接,在连接之前,此方法是阻塞的 System.out.println("connect to"+socket.getInetAddress()+":"+socket.getLocalPort()); new ConnectThread(socket).start(); } } catch (IOException e) { // Todo auto-generated catch block System.out.println("IOException"); e.printstacktrace(); } } //向客户端发送信息 class ConnectThread extends Thread{ Socket socket = null; public ConnectThread(Socket socket){ super(); this.socket = socket; } @OverrIDe public voID run(){ try { DatainputStream dis = new DatainputStream(socket.getinputStream()); DataOutputStream dos = new DataOutputStream(socket.getoutputStream()); while(true){ i++; String msgRecv = dis.readUTF(); System.out.println("msg from clIEnt:"+msgRecv); dos.writeUTF(msgRecv + i); dos.flush(); } } catch (IOException e) { // Todo auto-generated catch block e.printstacktrace(); } } }}
需要在线程中调用,调用方法:
new Thread(() -> new Server().startService()).start();
3、客户端代码
import androID.os.Bundle;import androID.os.Handler;import androID.os.Message;import androID.Widget.button;import androID.Widget.EditText;import androID.Widget.TextVIEw;import androID.Widget.Toast;import java.io.DatainputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.InetAddress;import java.net.socket;import java.net.UnkNownHostException;import androIDx.appcompat.app.AppCompatActivity;/** * @author fenghaitao * @time 2020年4月2日14:34:33 * scoket客户端连接测试 */public class SocketActivity extends AppCompatActivity { //IP地址和端口号 public static String IP_ADDRESS = ""; public static int PORT = 9998; //三个控件 EditText et_message = null; //需要发送的内容 button bt_getAdress = null; //获取本机IP地址 button bt_connect = null; //连接并发送 button bt_startServer = null; //启动服务端 TextVIEw tv_adress = null; //ip地址 TextVIEw tv_reply = null; //服务器回复的消息 //handler Handler handler = null; Socket soc = null; DataOutputStream dos = null; DatainputStream dis = null; String messageRecv = null; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_socket); et_message = findVIEwByID(R.ID.et_message); bt_getAdress = findVIEwByID(R.ID.bt_getAdress); bt_connect = findVIEwByID(R.ID.bt_connect); bt_startServer = findVIEwByID(R.ID.bt_startServer); tv_adress = findVIEwByID(R.ID.tv_adress); tv_reply = findVIEwByID(R.ID.tv_reply); bt_getAdress.setonClickListener(v -> { new Thread(() -> { try { InetAddress addr = InetAddress.getLocalHost(); System.out.println("local host:"+addr); runOnUiThread(() -> tv_adress.setText(addr.toString().split("/")[1])); } catch (UnkNownHostException e) { e.printstacktrace(); } }).start(); }); bt_startServer.setonClickListener(v -> { new Thread(() -> new Server().startService()).start(); Toast.makeText(SocketActivity.this,"服务已启动",Toast.LENGTH_SHORT).show(); }); bt_connect.setonClickListener(v -> { IP_ADDRESS = tv_adress.getText().toString(); new ConnectionThread(et_message.getText().toString()).start(); }); handler = new Handler(msg -> { Bundle b = msg.getData(); //获取消息中的Bundle对象 String str = b.getString("data"); //获取键为data的字符串的值 tv_reply.append(str); return false; }); } //新建一个子线程,实现socket通信 class ConnectionThread extends Thread { String message = null; public ConnectionThread(String msg) { message = msg; } @OverrIDe public voID run() { if (soc == null) { try { //Log.d("socket","new socket"); if ("".equals(IP_ADDRESS)) { return; } soc = new Socket(IP_ADDRESS, PORT); //获取socket的输入输出流 dis = new DatainputStream(soc.getinputStream()); dos = new DataOutputStream(soc.getoutputStream()); } catch (IOException e) { // Todo auto-generated catch block e.printstacktrace(); } } try { dos.writeUTF(message); dos.flush(); messageRecv = dis.readUTF();//如果没有收到数据,会阻塞 Message msg = new Message(); Bundle b = new Bundle(); b.putString("data", messageRecv); msg.setData(b); handler.sendMessage(msg); } catch (IOException e) { // Todo auto-generated catch block e.printstacktrace(); } } }}
下面是xml页面代码
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:app="http://schemas.androID.com/apk/res-auto" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" tools:context=".socketActivity"> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical"> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:layout_margintop="10dp"> <button androID:ID="@+ID/bt_getAdress" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="获取IP地址"/> <TextVIEw androID:ID="@+ID/tv_adress" androID:layout_wIDth="200dp" androID:layout_height="match_parent" androID:layout_marginleft="15dp" androID:textSize="20dp" androID:gravity="center"/> </linearLayout> <button androID:ID="@+ID/bt_startServer" androID:text="启动服务" androID:layout_margintop="10dp" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content"/> <EditText androID:ID="@+ID/et_message" androID:layout_margintop="10dp" androID:hint="请输入发送信息" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content"/> <button androID:ID="@+ID/bt_connect" androID:text="连接发送" androID:layout_margintop="10dp" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content"/> <TextVIEw androID:ID="@+ID/tv_reply" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_margintop="10dp" androID:text="服务端返回消息:" androID:textSize="30sp"/> </linearLayout></linearLayout>
客户端跟服务器进行通信之前记得先启动服务器,如果端口被占用需要换个端口。
总结以上是内存溢出为你收集整理的Android中socket通信简单实现全部内容,希望文章能够帮你解决Android中socket通信简单实现所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)