надеюсь, кто-то может помочь.Я просто пытаюсь установить соединение через сокет TCP между сервером Windows PC и телефоном Android.Во-первых, как определить, какой IP-адрес нужен.У меня ATT UVerse Broadband, и мой компьютер подключен к своей коробке через Ethernet.Согласно ATT:
https://www.att -services.net / tools / tool-ip-address-hostname.html
У меня есть один IP-адрес: 162.192.62.91,Согласно ipconfig, у меня есть другое: 192.168.1.67.Оба тайм-аута вызова accept () на ServerSocket, независимо от того, запущен клиент вскоре после вызова или нет.Что мне все равно нужно?Netstat точно отражает присутствие прослушивателя сервера до тех пор, пока код сервера не будет завершен, а затем отражает его отсутствие.Не уверен, что я делаю не так.Брандмауэр Windows в настоящее время выключен.Спасибо всем, кто на это посмотрит.Вот сервер java:
package my.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServerSocket {
static ServerSocket server;
static String addr = "192.168.1.67";
static int port = 8080;
InetAddress ia;
private MyServerSocket() throws Exception {
if (addr != null && !addr.isEmpty()) {
ia = InetAddress.getByName(addr); //ipAddress);
System.out.println("18 MSS InetAddress.getByName(" + addr + ") = " + ia);
try {
server = new ServerSocket(port, 1, ia);
System.out.println("20 MSS Nonempty ipAddress: instantiated ServerSocket");
} catch( IOException e) {
System.out.println("22 MSS while instantiating ServerSocket: " + e);
}
}
else {
ia = InetAddress.getLocalHost();
server = new ServerSocket(port, 1, ia);
System.out.print("28 MSS empty ipAddress: MSS new ServerSocket port ");
System.out.print(port);
System.out.println(", addr " + ia);
}
}
private void listen() throws Exception {
String data = null;
Socket client = server.accept(); //Hangs here
String clientAddress = client.getInetAddress().getHostAddress();
System.out.println("35 MSS New connection from " + clientAddress);
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
while ( (data = in.readLine()) != null ) {
System.out.println("40 MSS Message from " + clientAddress + ": " + data);
}
}
public static void main(String[] args) throws Exception {
MyServerSocket app = new MyServerSocket();
System.out.println("52 MSS instantiated MyServerSocket: " +
" Addr=" + server.getInetAddress() +
" Port=" + server.getLocalPort());
app.listen();
}
}
Клиент Android:
package my.androidsocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.util.Log;
public class AndroidClientSocket extends AsyncTask <String, Void, String>{
private static final String LOG_TAG = "ClientSocket";
static InputStream is = null;
private String serverHostOrIPAddr = "192.168.1.67"; //162.192.62.91 (can't assign addr)
//127.0.0.1 (refused) "listening on port 3306 (mysql) for local loopback only"
//192.168.1.67 (times out w an Exception) (from cmd->ipconfig-> ip4 address)
private String serverPortStr = "8080";
@Override
protected String doInBackground(String... params) {
Integer serverPort = Integer.parseInt(serverPortStr);
Log.d(LOG_TAG,"24 ACS connecting to host " + serverHostOrIPAddr +
" on port " + serverPort + ".");
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
//hangs, then returns null even when server is listening to the addr/port at startup
socket = new Socket(serverHostOrIPAddr, serverPort);
System.out.print("33 ACS Socket instantiation returned ");
System.out.println(socket);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String userInput = "a\r\n";
while (true) {
System.out.print("client: ");
//String userInput = stdIn.readLine();
/** Exit on 'q' char sent */
if ("q".equals(userInput)) {
break;
}
out.println(userInput); //out to console
userInput = "";
System.out.println("server: " + in.readLine()); //chars from server
}
} catch (UnknownHostException e) {
Log.d(LOG_TAG,"55 ACS while connecting to host " + serverHostOrIPAddr + ": " + e );
try {
socket.close();
} catch (IOException e1) {
Log.d(LOG_TAG,"59 ACS while closing socket " + e );
}
System.exit(1);
} catch (IOException e) {
Log.d(LOG_TAG,"63 ACS while connecting to host: " + e);
if(socket!=null) {
try {
socket.close();
} catch (IOException e1) {
Log.d(LOG_TAG,"68 ACS while closing socket: " + e);
}
}
System.exit(1);
}
String userInput = "user input...\r\n"; //Fake the user console input
out.println(userInput);
Log.d(LOG_TAG,"76 ACS user input sent to socket output stream: " + userInput);
out.close();
try {
in.close();
} catch (IOException e) {
Log.d(LOG_TAG,"82 ACS IOException closing input stream: " + e);
}
try {
socket.close();
} catch (IOException e) {
Log.d(LOG_TAG,"87 ACS IOException closing socket: " + e);
}
return "null";
}
}
и абонент Android:
package my.androidsocket;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AndroidClientSocket acs = new AndroidClientSocket( );
acs.execute();
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText("18 MA GET response: " + "null");
}
}
И вывод:
18 MSS InetAddress.getByName(192.168.1.67) = /192.168.1.671
20 MSS Nonempty ipAddress: instantiated ServerSocket: port=8080 bindAddr=/192.168.1.67