您好我是编程新手,在这里我尝试使用Android Studio上的Java,一个Android手机上的客户端套接字,另一个上的服务器套接字创建客户端 - 服务器套接字连接。无论我在同一台路由器上连接两部电话时使用的端口如何,代码都能正常工作,并使用内部IP(192.168.1.4)作为客户端套接字而不是全局IP(183.90.37.22)。但是,如果我打开4G连接并在我的代码中使用全局IP,则客户端套接字无法连接到另一部手机上的服务器套接字。然而,当使用端口80时,我设法看到祝酒词显示直到“消息已发送” ALTHOUGH 在使用服务器套接字编码的电话中显示没有消息/祝酒词。我非常感谢能得到的所有帮助,如果能够详细解释如何为客户端分配TCP端口,那将会很棒。可以给出服务器套接字! =)
首先呈现客户端套接字:
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MessageSenderThread messageSender = new MessageSenderThread("messageSender");
messageSender.start();
}
});
}
class MessageSenderThread extends Thread {
private String threadName;
private Thread t;
MessageSenderThread(String s) {
threadName = s;
}
@Override
public void run() {
try {
showToast("Connecting to server...");
Socket socket = new Socket("183.90.37.22", 80);
showToast("Connection established");
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.println("MESSAGE");
printWriter.flush();
showToast("Message sent");
outputStream.close();
outputStreamWriter.close();
printWriter.close();
socket.close();
showToast("Socket closed");
}
catch (IOException e) {
showToast("Connection FAILED");
}
}
@Override
public void start() {
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}
}
代码的服务器端如下所示:
MessageReceiverThread messageReceiverThread = new MessageReceiverThread("messageReceiver");
messageReceiverThread.start();
class MessageReceiverThread extends Thread {
private String threadName;
private Thread t;
MessageReceiverThread(String s) {
threadName = s;
}
@Override
public void run() {
try {
while (true) {
ServerSocket serverSocket = new ServerSocket(5000);
showToast("Server is listening...");
Socket socket = serverSocket.accept();
showToast("Connection established");
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String message = bufferedReader.readLine();
showToast(message);
inputStream.close();
inputStreamReader.close();
bufferedReader.close();
socket.close();
serverSocket.close();
}
} catch (IOException e) {
showToast("Connection FAILED");
}
}
答案 0 :(得分:0)
您的移动服务提供商阻止传入连接。
因此,在无法访问的设备上运行服务器是没有意义的。