###Service 端(手机A)
package com.example.administrator.dn_data_structure_01;
import android.util.Log;
import com.example.administrator.dn_data_structure_01.bean.MessageServer;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
private static ServerSocket serverSocket;
private static Socket socket;
public static void startServer(){
if (serverSocket == null){
new Thread(new Runnable() {
@Override
public void run() {
try {
serverSocket = new ServerSocket(1111);
Log.i("tcp" , "服务器等待连接中");
socket = serverSocket.accept();
Log.i("tcp" , "客户端连接上来了");
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
String data = new String(buffer, 0, len);
Log.i("tcp" , "收到客户端的数据-----------------------------:" + data);
EventBus.getDefault().post(new MessageServer(data));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
socket = null;
serverSocket = null;
}
}
}).start();
}
}
public static void sendTcpMessage(final String msg){
if (socket != null && socket.isConnected()) {
new Thread(new Runnable() {
@Override
public void run() {
try {
socket.getOutputStream().write(msg.getBytes());
socket.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
###Service端Activity
package com.example.administrator.dn_data_structure_01;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.administrator.dn_data_structure_01.bean.MessageServer;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends AppCompatActivity {
Button btnStartServer;
Button btnSrartClient;
Button btnSendToServer;
Button btnSendToClient;
TextView tv_server;
TextView tv_client;
EditText ed_message;
/**
* 服務端
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStartServer = findViewById(R.id.btn_start_server);
btnSendToClient = findViewById(R.id.btn_send_client);
ed_message = findViewById(R.id.ed_message);
tv_server = findViewById(R.id.tv_server);
btnStartServer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//开启服务器
TcpServer.startServer();
}
});
btnSendToClient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送数据给客户端
TcpServer.sendTcpMessage(ed_message.getText().toString());
ed_message.setText("");
}
});
Log.i("tcp" ,"ip地址:" + getIPAddress(this));
//注册EventBus
EventBus.getDefault().register(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void MessageServer(MessageServer messageEvent) {
tv_server.setText("");
tv_server.setText("服务器收到:" +messageEvent.getMsg());
}
public static String getIPAddress(Context context) {
NetworkInfo info = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
try {
//Enumeration en=NetworkInterface.getNetworkInterfaces();
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
return ipAddress;
}
} else {
//当前无网络连接,请在设置中打开网络
}
return null;
}
/**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
public static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
###Client 端(手机B)
package telephony.internal.android.com.sockserver;
import android.util.Log;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import telephony.internal.android.com.sockserver.bean.MessageClient;
/**
* Created by ybf on 2019/1/29.
*/
public class TcpClient {
public static Socket socket;
public static void startClient(final String address , final int port){
if (address == null){
return;
}
if (socket == null) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i("tcp", "启动客户端");
socket = new Socket(address, port);
Log.i("tcp", "客户端连接成功");
PrintWriter pw = new PrintWriter(socket.getOutputStream());
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
String data = new String(buffer, 0, len);
Log.i("tcp", "收到服务器的数据---------------------------------------------:" + data);
EventBus.getDefault().post(new MessageClient(data));
}
Log.i("tcp", "客户端断开连接");
pw.close();
} catch (Exception EE) {
EE.printStackTrace();
Log.i("tcp", "客户端无法连接服务器");
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
socket = null;
}
}
}).start();
}
}
public static void sendTcpMessage(final String msg){
if (socket != null && socket.isConnected()) {
new Thread(new Runnable() {
@Override
public void run() {
try {
socket.getOutputStream().write(msg.getBytes());
socket.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
###Activity
package telephony.internal.android.com.sockserver;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import telephony.internal.android.com.sockserver.bean.MessageClient;
/**
* 客戶端
*/
public class MainActivity extends Activity {
private String TAG = "tcp";
private TextView tv;
private EditText ed_tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
ed_tv = findViewById(R.id.ed_tv);
//注册EventBus
EventBus.getDefault().register(this);
initData();
}
private void initData() {
findViewById(R.id.btn_start_client).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TcpClient.startClient( "192.168.43.00" , 1111);
}
});
findViewById(R.id.btn_send_server).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TcpClient.sendTcpMessage(ed_tv.getText().toString());
ed_tv.setText("");
}
});
}
//收到客户端的消息
@Subscribe(threadMode = ThreadMode.MAIN)
public void MessageClient(MessageClient messageEvent) {
Log.e(TAG,"客户端收到:" + messageEvent.getMsg());
tv.setText("");
tv.setText("客户端收到:" + messageEvent.getMsg());
}
public static String getIPAddress(Context context) {
NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
try {
//Enumeration en=NetworkInterface.getNetworkInterfaces();
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
return ipAddress;
}
} else {
//当前无网络连接,请在设置中打开网络
}
return null;
}
/**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
public static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}