1
我試圖建立一個筆記本電腦作爲客戶端和PC作爲服務器之間的TCP連接。 我的目標是使用服務器在兩個android設備之間發送消息。該服務器有一個公共IP地址。要測試連接,我已經寫了兩個簡單的Java類:TcpSockets不連接
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public ServerSocket welcome;
public Socket soc;
public int listeningPort = /* default port */;
public TcpServer() {
}
public static void main(String[] args) {
TcpServer ms = new TcpServer();
if(args.length > 0) {
ms.listeningPort = Integer.parseInt(args[0]);
}
ms.listen();
}
public void listen() {
try {
welcome = new ServerSocket(listeningPort);
System.out.println(">>> listening on port " + listeningPort + " <<<");
soc = welcome.accept();
System.out.println(">>> got a new connection from "
+ soc.getInetAddress().toString() + " <<<");
while (true) {
try {
byte b[] = new byte[1024];
soc.getInputStream().read(b, 0, 1);
System.out.print((char) (b[0]));
} catch (Exception e) {
System.err.println(e);
}
}
} catch (Exception e) {
System.err.println(e);
}
}
}
import java.net.Socket;
public class TcpSendClient {
private String serverIp = /* some ip */;
public int port = /* default port */;
private SendThread st;
public TcpSendClient() {
}
public static void main(String[] args) {
TcpSendClient client = new TcpSendClient();
if(args.length > 0) {
client.port = Integer.parseInt(args[0]);
}
client.send();
}
public void send() {
System.out.println("Try to connet to " + serverIp + " via Port" + port);
st = new SendThread(serverIp, port);
st.start();
}
class SendThread extends Thread {
private Socket soc;
public SendThread(String theIp, int thePort) {
try {
soc = new Socket(theIp, thePort);
} catch (Exception e) {
System.err.println(e);
}
}
public void run() {
try {
while (true) {
String toSend = "Hello ";
soc.getOutputStream().write(toSend.getBytes());
Thread.sleep(800);
System.out.println("sent");
}
} catch (Exception e) {
System.err.println(e);
}
}
}
}
當我運行的服務器PC提供的Java文件,連接工作正常。如果我用一臺筆記本電腦設置本地Wi-Fi,並使用另一臺筆記本電腦連接到它,它也可以工作。 但是,當我從連接到互聯網的筆記本電腦運行客戶端文件時,我無法獲得連接。 在服務器的防火牆中,我打開了一些連接端口,並且我用作客戶端的筆記本電腦禁用了防火牆。 除了防火牆之外,我不知道爲了讓連接正常運行需要查看什麼。關於我的問題和解決方案的原因的任何想法?
NAT背後的服務器?你有沒有轉發正確的端口? – 2014-09-01 17:44:30
我不認爲它是在NAT後面。如果轉到whatismyip.com,我會得到與在命令窗口中輸入ipconfig時相同的地址。或者還有什麼我需要檢查? – ottofindichokay 2014-09-01 20:28:24