我正在尝试用Java构建一个简单的客户端 - 服务器套接字程序,其中交换基本信息。但是,只有第一条消息似乎在客户端和服务器之间传递,之后程序挂起。我展示了相关的代码。我提前道歉,但我从来没有使用Java或任何其他语言进行任何大量的套接字编程工作。
public static void main(String[] args) {
(new Thread(new SeederServer())).start();
for (int i=0; i < 1; ++i) {
(new Thread(new SeederClient())).start();
}
}
public class SeederServer implements Runnable {
Set<String> set = Collections.synchronizedSet(new HashSet<String>());
@Override
public void run() {
ServerSocket myServer = null;
Socket clientSocket = null;
try {
myServer = new ServerSocket(SeederMain.serverPort);
System.out.println(myServer.toString());
}
catch (IOException e) {
System.out.println(e);
}
while (true) {
try {
clientSocket = myServer.accept();
}
catch (IOException e) {
System.out.println(e);
}
new Thread(new SocketRunnable(clientSocket, set)).start();
}
}
}
public class SeederClient implements Runnable {
private Socket client = null;
@Override
public void run() {
try {
client = new Socket("localhost", SeederMain.serverPort);
}
catch (IOException e) {
System.out.println(e);
}
try {
BufferedReader in =
new BufferedReader(
new InputStreamReader(client.getInputStream()));
PrintStream os = new PrintStream(client.getOutputStream());
os.println(SeederMain.HELLO);
String line = in.readLine();
System.out.println("socket " + client.getLocalPort() + " received response: " + line);
for (int i=0; i < 10000; ++i) {
os.println(SeederMain.GET_LIST);
line = in.readLine();
if (line != null) {
System.out.println("socket " + client.getLocalPort() + " received response: " + line);
}
}
in.close();
os.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
public class SocketRunnable implements Runnable{
private Socket clientSocket = null;
private String serverText = null;
private Set<String> nodeSet;
public SocketRunnable(Socket clientSocket, Set<String> nodeSet) {
this.clientSocket = clientSocket;
this.nodeSet = nodeSet;
}
public void run() {
try {
BufferedReader in =
new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
OutputStream out = clientSocket.getOutputStream();
String input = in.readLine();
String output = "";
if (input.equals(SeederMain.HELLO)) {
nodeSet.add(String.valueOf(clientSocket.getLocalPort()));
output = SeederMain.HELLO;
}
else if (input.equals(SeederMain.GET_LIST)) {
output = nodeSet.toString();
}
else {
output = SeederMain.ERROR;
}
out.write(output.getBytes());
out.close();
in.close();
} catch (IOException e) {
//report exception somewhere.
e.printStackTrace();
}
}
}