【发布时间】:2014-01-15 15:28:25
【问题描述】:
我已经在 stackoverflow 中搜索了我的问题的答案,但我无法从这些线程中得到答案。我的问题是为什么一个ServeerSocket对象的accept()方法返回一个监听服务器机器上不同端口的Socket对象,而服务器正在监听的端口是另一个。
JAVA代码:
package chat.server;
import java.io.*;
import java.net.*;
public class ServerApp {
public String[] advices = {"Take smaller bites",
"Go for the tight jeans. No they do NOT make you look fat.",
"One word: inappropriate",
"Just for today, be honest. Tell your boss what you *really* think",
"You might want to rethink that haircut."};
public ServerSocket serverSocket;
public ServerApp()
{
try
{
serverSocket = new ServerSocket(4245);
System.out.println("Server Started.");
}catch (Exception exception)
{
exception.printStackTrace();
}
}
public static void main(String[] args) {
ServerApp server = new ServerApp();
while(true)
{
server.sendMessage();
}
}
public void sendMessage()
{
String advice;
try
{
Socket socket = serverSocket.accept();//here comes my question
System.out.println(socket.getPort());
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
advice = getAdvice();
printWriter.write(advice);
printWriter.close();
System.out.println(advice);
}catch (Exception exception)
{
exception.printStackTrace();
}
}
private String getAdvice() {
int random = (int) (Math.random() * advices.length);
return advices[random];
}
}
服务器从同一个端口号监听和应答客户端不是很正常吗?
【问题讨论】:
标签: java sockets networking port