랩톱을 클라이언트로, 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 뒤에 서버가 있습니까? 올바른 포트를 전달 했습니까? –
NAT 뒤에 있다고 생각하지 않습니다. whatismyip.com으로 이동하면 명령 창에 ipconfig를 입력 할 때와 동일한 주소가 표시됩니다. 아니면 확인해야 할 것이 있습니까? – ottofindichokay