packagetest.serv;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.OutputStreamWriter;importjava.net.InetAddress;importjava.net.InetSocketAddress;importjava.net.ServerSocket;importjava.net.Socket;importjava.net.UnknownHostException;importjava.util.Calendar;importjava.util.Date;importjava.util.regex.Pattern;public classServer {public static voidmain(String[] args) {//启动3000端口
int argnum =args.length;if (argnum < 2) {
System.out.println("请输入IP地址、端口,比如:172.17.201.127 3000");return;
}
String ipaddr= getIP(args[0]);int port = Integer.valueOf(args[1]);
startService(ipaddr,port);}
public static void startService(String ipaddr,intport){
ServerSocket server;
BufferedReader br= null;try{
server= newServerSocket();
server.setReuseAddress(true);
server.bind(newInetSocketAddress(ipaddr,port));
Socket sk= null;
String context= "---服务器端开始接收消息-----";
String filePath= "./log/"+getlognamebyweek();boolean isAppend = true;
String encoding= "UTF-8";while(true){
sk=server.accept();
context="nr";
writeStringToFile(context, filePath, isAppend, encoding);
br= newBufferedReader(newInputStreamReader(sk.getInputStream()));
context=br.readLine();
writeStringToFile(context, filePath, isAppend, encoding);
br.close();
context="nrnr";
writeStringToFile(context, filePath, isAppend, encoding);
}
}catch(IOException e){
System.out.println(e);
}finally{if (br!=null){try{
br.close();
}catch(IOException e) {//TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}public static void writeStringToFile(String context, String filePath, booleanisAppend, String encoding)
{
BufferedWriter bfw= null;try{
bfw= new BufferedWriter(new OutputStreamWriter(newFileOutputStream(filePath, isAppend), encoding));
bfw.write(context);
bfw.flush();
bfw.close();
}catch(IOException localIOException1)
{try{if (bfw != null)
bfw.close();
}catch(IOException e)
{
e.printStackTrace();
}
}finally{try{if (bfw != null)
bfw.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
public staticString getIP(String name) {
String pattern= "^[0-9]+.[0-9]+.[0-9]+.[0-9]+$";boolean isIP =Pattern.matches(pattern, name);if(isIP) {returnname;
}
InetAddress address= null;try{
address=InetAddress.getByName(name);
}catch(UnknownHostException e) {
e.printStackTrace();
System.out.println("获取失败");
}returnaddress.getHostAddress().toString();
}
public staticString getlognamebyweek(){
Date date=newDate();
Calendar c=Calendar.getInstance();
c.setTime(date);//今天是这个星期的第几天
int week=c.get(Calendar.DAY_OF_WEEK)-1;return week+".log";
}
}



