我试图在Android中通过TCP套接字发送消息,但它不起作用。(我的手机是客户端)下面是来自类 TCPClient 的代码:public class TcpClient { public static String SERVER_IP = "192.168.200.1"; //server IP address public static final int SERVER_PORT = 1500; // message to send to the server private String mServerMessage; // sends message received notifications private OnMessageReceived mMessageListener = null; // while this is true, the server will continue running private boolean mRun = false; // used to send messages private PrintWriter mBufferOut; // used to read messages from the server private BufferedReader mBufferIn; private Socket socket; private Context context; /** * Constructor of the class. OnMessagedReceived listens for the messages received from server */ public TcpClient(OnMessageReceived listener) { mMessageListener = listener; } /** * Sends the message entered by client to the server * * param message text entered by client */ public String sendMessage(String message) { byte[] bytesToSend = message.getBytes(); if (bytesToSend != null && socket != null && socket.isConnected()) { try { socket.getOutputStream().write(bytesToSend, 0, 9); return "deu"; } catch (Exception e2) { e2.printStackTrace(); return e2.getMessage(); } } else return "aa"; } /** * Close the connection and release the members */ public void stopClient() { sendMessage("disconnecting"); mRun = false; if (mBufferOut != null) { mBufferOut.flush(); mBufferOut.close(); } mMessageListener = null; mBufferIn = null; mBufferOut = null; mServerMessage = null; }
1 回答
桃花长相依
TA贡献1860条经验 获得超8个赞
无需为你的英语感到抱歉!它完全没:)
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1598)
当您的应用程序尝试在主线程上执行任何网络操作时,将引发上述错误。
您可以使用下面的代码强制操作或创建单独的线程并执行操作。
备选案文1:强迫
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
}
选项 2:单独的螺纹
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// do something in here
}
});
thread.start();
添加回答
举报
0/150
提交
取消