我需要通过使用套接字编程在同一台PC上的模拟器之间发送消息,第一个模拟器的行为类似于服务器,第二个模拟器就像客户端一样。但我无法调用我的服务器模拟器并传递消息。我是android的新手可以任何身体PLZ帮助我。
我的代码
服务器端代码
package com.test.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class ServerActivity extends Activity {
private TextView serverStatus;
// DEFAULT IP
public static String SERVERIP = "192.168.0.20"; // 10.0.2.15
// DESIGNATE A PORT
public static final int SERVERPORT = 4000; // 8080
private Handler handler = new Handler();
private ServerSocket serverSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
@Override
public void run() {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
@Override
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端代码:
package com.test.android;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "192.168.0.20"; // 10.0.2.15 // machin ip 192.168.0.20 // default ip:- 10.0.2.2
private boolean connected = false;
private Handler handler = new Handler();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")){
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
});
}
}
档案ClientThread.java
:
package com.test.android;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.util.Log;
import android.widget.EditText;
public class ClientThread implements Runnable {
private String serverIpAddress = "192.168.0.20"; //10.0.2.15
private boolean connected = false;
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected){
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
// TODO: handle exception
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
}
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
答案 0 :(得分:0)
我没有尝试过您的代码,但我认为您应该使用70作为SERVERPORT。
答案 1 :(得分:0)
以下内容适用于我在macOS Big Sur 11.1上的Android Studio 4.1.1开发环境中。这是一个通过套接字的简单国际象棋游戏。
要在仿真器上设置端口重定向,请转到终端。
要找出仿真器控制台使用的端口号,请运行
~/Library/Android/sdk/platform-tools/adb devices
要查找身份验证令牌,请运行
cat ~/.emulator_console_auth_token
运行到telnet仿真器控制台(假设端口号为5554)
telnet localhost 5554
要获得身份验证,请运行
auth your_auth_token
要列出活动的重定向,请运行
redir list
添加重定向,运行(假设50000是主机端口,而50001是来宾端口)
redir add tcp:50000:50001
要返回telnet提示,请按
ctrl + ]
退出telnet,运行
close
科特林(Kotlin)的Android国际象棋: https://github.com/zhijunsheng/chess-kotlin-andr
UIKit的iOS国际象棋(用作测试套接字客户端): https://github.com/zhijunsheng/chess-uikit-ios