客户端服务器实施:
客户端必须等到服务器从用户读取输入( socket.getInputStream())。我只想等待服务器响应5秒钟。
1。服务器客户端连接后
2。服务器将数据发送到客户端
3。客户端读取数据直到服务器发送(我只想等待5秒)
客户:
public class SocketClientExample {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{
//get the localhost IP address, if server is running on some other IP, you need to use that
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
for(int i=0; i<10;i++){
//establish socket connection to server
socket = new Socket(host.getHostName(), 9876);
//write to socket using ObjectOutputStream
oos = new ObjectOutputStream(socket.getOutputStream());
if(i==8)oos.writeObject("exit");
else oos.writeObject(""+i);
//read the server response message
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
//close resources
ois.close();
oos.close();
Thread.sleep(100);
}
}
}
服务器:
public class SocketServerExample {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 9876;
public static void main(String args[]) throws IOException, ClassNotFoundException, InterruptedException{
//create the socket server object
server = new ServerSocket(port);
server.setSoTimeout(5000);
//keep listens indefinitely until receives 'exit' call or program terminates
int i=1;
while(true){
System.out.println("Waiting for client request");
//creating socket and waiting for client connection
try{
Socket socket = server.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//write object to Socket
i++;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
oos.writeObject("Hi Client "+br.readLine());
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}catch(Exception e){
System.out.println(e.getMessage());
}
//read from socket to ObjectInputStream object
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}