나는 안드로이드 2.2를 실행하는 나의 htc 욕망에 내 PC와 간단한 클라이언트에서 실행되는 간단한 서버를 가지고있다.간단한 안드로이드 클라이언트 및 PC 서버를 얻는 방법
서버와 클라이언트 모두 동일한 포트를 사용합니다. 나는 서버 코드를 클라이언트 코드로 하드 코딩한다.
IOException ...: java.net.SocketException: The operation timed out.
다음은 클라이언트와 서버 코드의 일부입니다 :
클라이언트 코드
InetAddress addr;
Socket socket = null;
byte [] ipAddress = new byte[] {(byte)82,(byte)168,(byte)175,(byte)141};
try{
addr = InetAddress.getByAddress(ipAddress);
socket = new Socket(addr, 1234);
System.out.println("socket = "+socket);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
out.println("hello");
socket.close();
} catch (UnknownHostException e) {
System.out.println("UnknownHostException ...: "+e);
} catch (IOException e) {
System.out.println("IOException ...: "+e);
}
나는 안드로이드 클라이언트에서 클라이언트를 통해 실행중인 서버에 연결하려고하면이 예외를 throw ,
서버 코드
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Started:"+ss);
try{
//block until a connection occures
Socket socket = ss.accept();
try{
System.out.println("Conncetion accepted:"+socket);
InputStream IS = socket.getInputStream();
InputStreamReader ISR = new InputStreamReader(IS);
BufferedReader in = new BufferedReader(ISR);
OutputStream OS = socket.getOutputStream();
OutputStreamWriter OSR= new OutputStreamWriter(OS);
BufferedWriter BW = new BufferedWriter(OSR);
//output automatically flushed by PrintWriter
PrintWriter out = new PrintWriter(BW,true);
while(true){
String str = in.readLine();
System.out.println("Client: "+str);
out.println("hi");
}
}finally{
System.out.println("Closing...");
socket.close();
}
}finally{
ss.close();
}
이 코드는 3g가 아닌 wifi를 사용하여 작동합니다.
도움을 주시면 ... 미리 감사드립니다.
켄고, 답장을 보내 주셔서 감사합니다. 이것은 NAT가 있다면 tcp 연결이 없다는 것을 의미합니다. 아니면 이것에 대한 해결책이 있습니까? – mnish
NAT는 인바운드 (inet-to-PC) 연결을 허용하지 않습니다. 이에 대한 해결책은 포트 포워딩입니다. –