我是套接字编程的新手,只是尝试使用一个小程序来掌握套接字的工作原理。有一个客户端和一个服务器,我只是想从服务器和显示中加载一些字符串。但是,即使我在finally块中手动清理了所有资源,但每次创建服务器套接字时,都会得到java.net.BindException
。请看下面的代码,并建议对可能导致此问题的内容进行一些编辑。我正在使用Eclipse。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class AdviceServer {
String[] adviceList = {
"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 void setUpServer() {
ServerSocket serverSocket = null;
try {
if (serverSocket == null)
serverSocket = new ServerSocket(8003);
int i = 2;
// Keep looping till we have clients.
while (true) {
Socket sock = serverSocket.accept();
PrintWriter pw = new PrintWriter(sock.getOutputStream());
pw.write(getRandomAdvice());
pw.close();
System.out.println(getRandomAdvice());
}
// serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void setUpClient() {
// Make a socket
Socket chatSocket = null;
try {
chatSocket = new Socket("127.0.0.1", 8003);
InputStreamReader isr = new InputStreamReader(
chatSocket.getInputStream());
// Make a chain stream Buffered Reader
BufferedReader br = new BufferedReader(isr);
String text;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (chatSocket != null) {
try {
chatSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getRandomAdvice() {
return adviceList[(int) (Math.random() * adviceList.length)];
}
public static void main(String[] args) {
AdviceServer as = new AdviceServer();
as.setUpClient();
as.setUpServer();
}
}
任何帮助将不胜感激,因为我已尽一切努力来纠正此问题。
最佳答案
您必须运行两次代码,因此得到BindException
。如在第一次运行中,服务器将在端口8003上运行并侦听,并且将出现ConnectionRefused
错误。下次运行此程序时,客户端将在再次运行服务器代码时,从服务器获取消息,后跟BindException
。
问题是服务器和客户端在同一主线程上运行。尝试在其他线程中运行服务器。并且还首先运行服务器,它将监听客户端的连接。