题目:
设计一个程序,服务器端记录他所接受的客户端,每10秒服务器轮询客户端一次,轮询指服务器发送字符串,客户端响应同样的报文。当轮询一个客户端三次,客户端无响应,服务器删除该客户端,删除客户端对应的socket。
解答:
1.服务端代码
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Objects;
import java.util.Vector;
public class TcpServer {
public static void main(String[] args) throws Exception{
List<MySocket> list = new Vector<>();
try{
System.out.println("服务端已就绪。。。");
ServerSocket serverSocket = new ServerSocket(8088);
Thread thread = new Thread(()->{
try {
//开始轮询
while (true){
Thread.sleep(10000);
System.out.println("总连接数:" + list.size());
for (int i = 0; i < list.size(); i++){
MySocket mySocket = list.get(i);
if(mySocket.socket.isConnected()){
try {
OutputStream outputStream = mySocket.socket.getOutputStream();
outputStream.write("hello,world!".getBytes());
InputStream inputStream = mySocket.socket.getInputStream();
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
System.out.println("来自客户端:" + new String(bytes));
} catch (IOException e) {
mySocket.lostNum = mySocket.lostNum + 1;
}
}else{
mySocket.lostNum = mySocket.lostNum + 1;
}
}
//删除三次轮询无结果的连接
for (int i = 0; i < list.size(); i++){
MySocket mySocket = list.get(i);
if(mySocket.lostNum == 3){
System.out.println("删除连接:" + mySocket.socket.getInetAddress() + ":" + mySocket.socket.getPort());
list.remove(mySocket);
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
while (true){
System.out.println("检测新连接");
Socket socket = serverSocket.accept();
socket.isConnected();
list.add(new MySocket(socket));
}
}catch (Exception e){
e.printStackTrace();
}
}
static class MySocket{
private Socket socket;
private int lostNum = 0;
public MySocket(Socket socket) {
this.socket = socket;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public int getLostNum() {
return lostNum;
}
public void setLostNum(int lostNum) {
this.lostNum = lostNum;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MySocket mySocket = (MySocket) o;
return socket.equals(mySocket.socket);
}
@Override
public int hashCode() {
return Objects.hash(socket);
}
}
}
2.客户端代码
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TcpClient {
public static void main(String[] args){
try{
Socket socket = new Socket("127.0.0.1",8088);
if(socket.isConnected()){
while (true){
InputStream inputStream = socket.getInputStream();
if(inputStream.available() != 0){
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
System.out.println("收到服务器的信息:" + new String(bytes));
OutputStream outputStream = socket.getOutputStream();
outputStream.write(bytes);
}
}
}else{
System.out.println("服务器无响应");
}
}catch (Exception e){
e.printStackTrace();
}
}
}