Android中socket通信简单实现
短信预约 -IT技能 免费直播动态提醒
Android中socket通信简单实现
作者:feng海涛
socket通信需要有一个服务器和客户端,可以把同一个APP作为服务器跟客户端,也可以分开成两个APP。
先上个图:
这里以一个APP作为服务器跟客户端为示例
1、添加网络访问权限
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;
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页面代码
客户端跟服务器进行通信之前记得先启动服务器,如果端口被占用需要换个端口。
作者:feng海涛
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341