import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.nio.charset.StandardCharsets;
import java.util.Date;
public class Server implements Runnable{
public static final String Credit = "2021";
String name="帅帅帅";
public static int flat=0;
Socket socket;
Server(Socket socket){
this.socket = socket;
}
public static void main(String[] args) throws IOException{
// 创建ServerSocket对象,指定监听的端口号
ServerSocket serverSocket = new ServerSocket(3000);
System.out.println("等待客户端连接...");
while(true){
// 监听客户端的连接请求
Socket clientSocket = serverSocket.accept();
System.out.println("客户端已连接");
new Thread(new Server(clientSocket)).start();
}
}
@Override
public void run(){
try {
OutputStream os = this.socket.getOutputStream();
InputStream in = this.socket.getInputStream();
byte[] buffer = new byte[1024];
int len = in.read(buffer);
String message = new String(buffer, 0, len,"utf-16le");
if (message.equalsIgnoreCase("exit")) {
}
else if(message.equals("gettime")){
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
os.write(df.format(date).getBytes(StandardCharsets.UTF_16LE));
os.flush();
}
//发送test 后面的内容
else if(message.startsWith("test")){
os.write(message.substring(5).getBytes(StandardCharsets.UTF_16LE));
}
else if(message.startsWith("auth")){
String content = message.substring(5);
if(content.equals(Credit) ){
os.write((new String("ok")).getBytes(StandardCharsets.UTF_16LE));
}
else{
os.write((new String("error")).getBytes(StandardCharsets.UTF_16LE));
}
}
else if(message.startsWith("auth2")){
String content = message.substring(6);
if(content.equals(name) ){
os.write((new String("ok")).getBytes(StandardCharsets.UTF_16LE));
}
else{
os.write((new String("error")).getBytes(StandardCharsets.UTF_16LE));
}
}
else {
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
PS:此程序是分布式计算的课堂作业,实现客户端和服务器端的通讯,老师提供的是C#程序,笔者采用的是Java,两者字符集编码不同,因此需要将Java中的语句输出字符集转为UTF_16LE。