我正在开发一个Android应用程序,它必须在两部手机之间进行实时通信。两部手机上都运行了一个客户端和服务器,我有一个中央服务器,每个服务器的公共IP和端口都是交换的。电话正在收听中央服务器的通知。
假设两部手机通过中央服务器接收对方的公共IP和端口,然后在每部手机上我启动客户端,然后是服务器(这是因为,它以其他顺序失败,因为我正在做洞打孔我使用相同的端口进行收听和发送。)
以下是我启动服务器和客户端的方法
socket=new Socket();
try {
socket.setReuseAddress(true);
} catch (SocketException e) {
e.printStackTrace();
}
try {
socket.bind(new InetSocketAddress(<Port of this phone>));
} catch (IOException e) {
e.printStackTrace();
}
ClientThread clientThread=new ClientThread(<IP of the other phone>,<Port of the other phone>,socket);
clientThread.execute();
Thread serverThread = new Thread(new ServerThread(<IP of this phone>,<Port of this phone>));
serverThread.start();
这是我服务器的代码
public class ServerThread implements Runnable {
private String serverIP;
private int serverPort;
private ServerSocket serverSocket;
public ServerThread(String serverIP,int serverPort){
this.serverIP=serverIP;
this.serverPort=serverPort;
}
public void run() {
try {
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(serverPort));
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
Log.d("serverstatus","Connected :)");
if(connected)
//then pass messages
}
}
catch (Exception e) {
Log.d("serverstatus","Error");
e.printStackTrace();
}
}
}
这是我客户的代码
public class ClientThread extends AsyncTask<String,String,String>{
private String serverIP;
private int serverPort;
private Socket socket;
public ClientThread(String serverip,int serverport,Socket mySocket)
{
serverIP=serverip;
serverPort=serverport;
socket=mySocket;
}
@Override
protected String doInBackground(String... arg0) {
try {
while(true)
{
socket.connect(new InetSocketAddress(serverIP, serverPort));
if(socket.isConnected())
{
//pass messages
}
}
}
catch (Exception e) {
Log.d("clientstatus","Error");
e.printStackTrace();
//try again
ClientThread clientThread=new ClientThread(serverIP,serverPort,socket);
clientThread.execute();
}
}
}
预期的是,在第一次从phone1到phone2的连接尝试失败后(因为phone2的端口尚未打开),phone1的端口开启(因为对phone2的请求),然后当phone2尝试与phone1通信时,它成功,因为phone1的端口现在是打开的,因此phone2的端口也是如此(因为phone2对phone1的请求)。
每当我尝试连接时,它仍显示Connection Refused,然后抛出'socket closed'异常。
我做错了什么,有人可以帮我解决这个问题。
答案 0 :(得分:0)
我尝试过类似OSx和iOS。我在服务器端有一个非常简单的C代码,用于监听传入连接,这是捕获手机的IP和端口号,如172.39.33.23:44392(基本上即使你的手机与wifi路由器连接,我能够从另一台设备向此端口发送数据)。但是,您应该尝试使用数据报(Java)将带有UDP的数据发送到捕获的ip和端口。
public void sendUdpData()
{
String phone1Ip = "172.39.33.23";
int phone1Port = 44392;
try
{
String commandString = "Send this data";
byte[] commnadByte = commandString.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(commnadByte, commnadByte.length,InetAddress.getByName(phone1Ip),phone1Port);
DatagramSocket datagramSocket= new DatagramSocket(phone1Port);
datagramSocket.send(datagramPacket);
datagramSocket.close();
}
catch (UnknownHostException e1)
{
}
catch (SocketException e1)
{
}
catch (IOException e1)
{
}
}