Java Wifi套接字地址无效,Android
每当我创建ServerSocket并通过调用getLocalSocketAddress查看套接字地址时,我都会看到: 0.0.0.0/0.0.0.0:xxxxx xxxx为随机端口号 我的服务器代码是:Java Wifi套接字地址无效,Android,java,android,sockets,Java,Android,Sockets,每当我创建ServerSocket并通过调用getLocalSocketAddress查看套接字地址时,我都会看到: 0.0.0.0/0.0.0.0:xxxxx xxxx为随机端口号 我的服务器代码是: try{ Boolean end = false; ServerSocket ss = new ServerSocket(0); System.out.println("Program running, Server address:" + ss.getLocalSock
try{
Boolean end = false;
ServerSocket ss = new ServerSocket(0);
System.out.println("Program running, Server address:" + ss.getLocalSocketAddress().toString());
while(!end){
//Server is waiting for client here, if needed
Socket s = ss.accept();
System.out.println("Socket Connected !");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
System.out.println("Tcp Example From client: "+st);
output.println("Good bye and thanks for all the fish :)");
s.close();
}
ss.close();
} catch (Exception ex) {
ex.printStackTrace();
}
不在ServerSocket中分配0
端口从0-65535,但要使用其1-65534。。此外,请尝试使用1024以上的端口,因为其他著名的服务(如Telnet、FTP、HTTP等)也会使用这些端口
查看我的代码…它可能会帮助您执行代码
服务器端代码示例:
注:1。您应该使用Log而不是System.out.println 2。ss超出范围,例如,编译器应该抱怨它是未知变量。对不起,没有粘贴整个代码。没有编译器错误,这只是因为整个代码没有进入我问题中的代码部分,这就是为什么我没有复制整个代码。我想现在的问题不在于服务器代码,我正在尝试在android设备和我的计算机之间交换数据包。那么在客户端代码中应该使用什么套接字地址呢?@Kumar Vivek Mitra:根据文档:public ServerSocket int port-构造一个绑定到给定端口的新ServerSocket实例。待办事项设置为50项。如果端口==0,端口将由操作系统分配。@bicska88我有一个疑问。。如果是由操作系统分配的,客户端如何知道服务器运行在哪个端口上。@Kumar Vivek Mitra:你说的没错,我想指出的是,这绝对不是问题的原因。@David Kroukamp,为什么要使用公共IP,他是否有一个静态的公共IP地址,我打赌如果是他的家庭电脑,它将使用NAT,如果是这样的话,他需要使用一些机制将他的动态IP作为静态。。。现在,如果他想运行该应用程序来测试代码,他可以使用任何IP,公共或私人,在他在互联网上使用该应用程序之前都无所谓。。。
public class ServerTest {
ServerSocket s;
public void go() {
try {
s = new ServerSocket(4445);
while (true) {
Socket incoming = s.accept();
Thread t = new Thread(new MyCon(incoming));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class MyCon implements Runnable {
Socket incoming;
public MyCon(Socket incoming) {
this.incoming = incoming;
}
@Override
public void run() {
try {
PrintWriter pw = new PrintWriter(incoming.getOutputStream(),
true);
InputStreamReader isr = new InputStreamReader(
incoming.getInputStream());
BufferedReader br = new BufferedReader(isr);
String inp = null;
boolean isDone = true;
System.out.println("TYPE : BYE");
System.out.println();
while (isDone && ((inp = br.readLine()) != null)) {
System.out.println(inp);
if (inp.trim().equals("BYE")) {
System.out
.println("THANKS FOR CONNECTING...Bye for now");
isDone = false;
s.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
try {
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ServerTest().go();
}
}