每当我创建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.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();
}
答案 0 :(得分:0)
不要在ServerSocket中分配“0”
端口是0-65535,但是它的1 - 65534要使用.. MoreOver尝试使用1024以上的端口,因为它被其他众所周知的服务使用,如Telnet,FTP,HTTP等。 强>
查看我的代码......它可能有助于您执行代码.....
服务器端代码示例:
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();
}
}