Android Socket client (Socket communication)

1. Start Socket port monitoring on the server

  Here it is set to 0.0.0.0:37280, which is to listen to all ips arriving at the server


2. Android client, connect to the server

  Fill in the ip address of the server and connect


Sample demo download

Sample source code download


Android Socket client core source code:


package sci.tool;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.Executors;


/** SocketClient.java: 对Socket进行简单接口封装,便于使用。
 * 
 * 用法:
 * client = new SocketClient(print, ipString, port);	// 创建客户端Socket操作对象
 * client.start();										// 连接服务器
 * client.Send(data);									// 发送信息
 * client.disconnect();									// 断开连接
 * 
 * ----- 2019-6-18 下午5:36:25 scimence */
public class SocketClient
{
	public String ipString = "127.0.0.1";   // 服务器端ip
	public int port = 37280;                // 服务器端口
	
	public Socket socket;
	public SocketCallBack call;				// 数据接收回调方法
	
	public SocketClient(SocketCallBack print, String ipString, int port)
	{
		this.call = print;
		if (ipString != null) this.ipString = ipString;
		if (port >= 0) this.port = port;
	}
	
	/** 创建Socket并连接 */
	public void start()
	{
		if (socket != null && socket.isConnected()) return;
			
		Executors.newCachedThreadPool().execute(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					if (socket == null)
					{
						InetAddress ip = InetAddress.getByName(ipString);
						socket = new Socket(ip, port);
						
						if (call != null) call.Print("服务器已连接 -> " + ip + ":" + port);
					}
				}
				catch (Exception ex)
				{
					if (call != null) call.Print("连接服务器失败 " + ex.toString()); // 连接失败
				}
				
				// Socket接收数据
				try
				{
					if (socket != null)
					{
						InputStream inputStream = socket.getInputStream();
						
						// 1024 * 1024 * 3 = 3145728
						byte[] buffer = new byte[3145728];		// 3M缓存
						int len = -1;
						while (socket.isConnected() && (len = inputStream.read(buffer)) != -1)
						{
							String data = new String(buffer, 0, len);
							
							// 通过回调接口将获取到的数据推送出去
							if (call != null)
							{
								call.Print("接收信息 -> " + data);
							}
						}
						
					}
				}
				catch (Exception ex)
				{
					if (call != null) call.Print("接收socket信息失败" + ex.toString()); // 连接失败
					socket = null;
				}
			}
		});
		
	}
	
	/** 发送信息 */
	public void Send(String data)
	{
		try
		{
			if(socket != null && socket.isConnected())
			{
				byte[] bytes = data.getBytes();
				OutputStream outputStream = socket.getOutputStream();
				outputStream.write(bytes);
				
				if (call != null) call.Print("发送信息 -> " + data);
			}
			else
			{
				if (call != null) call.Print("未连接服务器!清先连接后,再发送。");
			}
		}
		catch (Exception ex)
		{
			if (call != null) call.Print("发送socket信息失败!");
		}
	}
	
	/** 断开Socket */
	public void disconnect()
	{
		try
		{
			if (socket != null && socket.isConnected())
			{
				socket.close();
				socket = null;
				
				if (call != null) call.Print("服务器已断开! ");
			}
		}
		catch (Exception ex)
		{
			if (call != null) call.Print("断开socket失败!");
		}
	}
}
package sci.tool;

/**  
 * SocketCallBack.java: Socket信息回调逻辑
 * -----
 * 2019-6-18 下午5:41:56
 * scimence 
 */
public abstract class SocketCallBack
{	
	public abstract void Print(String info);
}

Android Socket demo demo:


package sci.demo.androidautofit;

import sci.tool.ActivityComponent;
import sci.tool.SocketCallBack;
import sci.tool.SocketClient;
import sci.tool.ThreadTool;
import sci.tool.ThreadTool.ThreadPram;
import android.os.Bundle;


/** Android Socket 演示demo主界面 */
public class MainActivity extends ActivityComponent
{
	
	SocketClient client = null;
	
	/** 设置界面显示 */
	@Override
	public void Init(Bundle savedInstanceState)
	{
		this.setContentView("activity_main");
	}
	
	/** 按钮点击响应逻辑 */
	@Override
	public void Click(String viewId)
	{
		if (viewId.equals("btn_connect"))
		{
			if (client == null)
			{
				SocketCallBack print = new SocketCallBack()
				{
					@Override
					public void Print(String info)
					{
						showMsg(info);
					}
				};
				
				String ipString = EditText("editIp").getText().toString();					// 服务器端ip地址如: 10.80.8.201
				int port = Integer.parseInt(EditText("editPort").getText().toString());		// 服务器端的监听端口如: 37280
				
				client = new SocketClient(print, ipString, port);	// 创建客户端Socket操作对象
			}
			
			if (client != null) client.start();						// 连接服务器
		}
		else if (viewId.equals("btn_close"))
		{
			client.disconnect();									// 断开连接
		}
		else if (viewId.equals("btn_send"))
		{
			String data = EditText("editMsg").getText().toString();
			client.Send(data);										// 发送信息
		}
	}
	
	/** 在信息显示区显示信息 */
	private void showMsg(final String msg)
	{
		ThreadTool.RunInMainThread(new ThreadPram()
		{
			@Override
			public void Function()
			{
				String content = TextView("textMSG").getText().toString();
				TextView("textMSG").setText(msg + "\r\n" + content);
				
				// ScrollView("msg_scroll").fullScroll(ScrollView.FOCUS_DOWN);
			}
		});
	}
}

Server-side source code reference: https://blog.csdn.net/scimence/article/details/52957829

Guess you like

Origin blog.csdn.net/scimence/article/details/92832245