还是一个socket的问题,大人物们,谢谢了!
这是一个多客户端的服务器上的代码,我的问题是:为什么在给每个客户打开一个thread后
在thread里的run中为什么还有个死循环while(true),它有什么作用?但运行后,确不会一直
运行那个死循环?
见代码:(第二个while(true))
// MultiThreadsServer.java: The server can communicate with
// multiple clients concurrently using the multiple threads
import java.io.*;
import java.net.*;
public class MultiThreadServer
{
// Main method
public static void main(String[] args)
{
try
{
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
// To number a client
int clientNo = 1;
Socket connectToClient = serverSocket.accept();
while (true)
{
// Listen for a new connection request
// Print the new connect number on the console
System.out.println("Start thread for client " + clientNo);
// Find the client's hostname, and IP address
InetAddress clientInetAddress =
connectToClient.getInetAddress();
System.out.println("Client " + clientNo + "'s hostname is "
+ clientInetAddress.getHostName());
System.out.println("Client " + clientNo + "'s IP Address is "
+ clientInetAddress.getHostAddress());
// Create a new thread for the connection
HandleAClient thread = new HandleAClient(connectToClient, clientNo);
// Start the new thread
thread.start();
// Increment clientNo
clientNo++;
}
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
// Define the thread class for handling a new connection
class HandleAClient extends Thread
{
private Socket connectToClient; // A connected socket
private int clientNo; // Indicate client no
// Construct a thread
public HandleAClient(Socket socket, int clientNo)
{
connectToClient = socket;
this.clientNo = clientNo;
}
// Implement the run() method for the thread
public void run()
{
try
{
// Create data input and output streams
DataInputStream isFromClient = new DataInputStream(
connectToClient.getInputStream());
DataOutputStream osToClient = new DataOutputStream(
connectToClient.getOutputStream());
// Continuously serve the client
while (true) //就是这个,为什么要用?
{
// Receive radius from the client
double radius = isFromClient.readDouble();
System.out.println("radius received from client " +
clientNo + ": " + radius);
// Compute area
double area = radius*radius*Math.PI;
// Send area back to the client
osToClient.writeDouble(area);
System.out.println("Area found: " + area);
}
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}