📄 server.java
字号:
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server{
ServerSocket serverSocket; // 创建服务器端套接字
private final int SERVER_PORT = 8049; //定义端口号
public Server(){
try{
serverSocket=new ServerSocket(SERVER_PORT); // 启动服务
System.out.println("Server started...");
System.out.println("Server port is:"+SERVER_PORT);
getIP(); // 得到并显示服务器端IP
while(true){ // 监听客户端的连接请求,并返回客户端socket
Socket socket=serverSocket.accept();
new ServerThread(socket); // 创建一个新线程来处理与该客户的通讯
}
}
catch(IOException e){
System.out.println("[ERROR] Cound not start server."+e);
}
}
public void getIP(){ // 得到服务器IP地址并显示
try{
InetAddress localAddress = InetAddress.getLocalHost();
byte[] ipAddress = localAddress.getAddress();
System.out.println("ServerIPis:"+(ipAddress[0]&0xff)+"."+ (ipAddress[1]&0xff)+"."+(ipAddress[2]&0xff)+"."+(ipAddress[3]&0xff));
}
catch(Exception e){
System.out.println("[ERROR] Cound not get IP."+e);
}
}
public static void main(String args[]){ // 实例化服务器端程序
new Server();
}
}
//接收到客户端socket发来的信息后进行解析、处理、转发。
class ServerThread extends Thread{
private Socket socket;//定义客户端套接字
private BufferedReader in;// 定义输入流
private PrintWriter out;// 定义输出流
private static Vector onlineUser = new Vector(10,5);
private static Vector socketUser = new Vector(10,5);
private String strReceive, strKey;
private StringTokenizer st;
private final String USERLIST_FILE = "d:\\user.txt"; //设定存放用户信息的文件
public ServerThread(Socket client) throws IOException{
socket = client;
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));//客户端接收
out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getoutput.Stream())),true);//客户端输出
this.start();
}
public void run(){
try{
while(true){ //从服务器端接收一条信息后拆分、解析,并执行相应操作
strReceive = in.readLine();
st = new StringTokenizer(strReceive,"|");
strKey = st.nextToken();
if(strKey.equals("login")){
login();
}
else if(strKey.equals("talk")){
talk();
}
else if(strKey.equals("init")){
initClientOnline();
}
else if(strKey.equals("reg")){
register();
}
}
}
catch(IOException e){ //用户关闭客户端造成此异常,关闭该用户套接字。
String leaverUser = closeSocket();
System.out.println("[SYSTEM] "+leaverUser+" leaver JAVA chat!");
sendAll("talk|>>>"+leaverUser+" 恋恋不舍的离开了聊天室。");
}
}
private boolean isExistUser(String name){ // 判断是否有该注册用户
String strRead;
try{
FileInputStream inputfile = new FileInputStream(USERLIST_FILE);
DataInputStream inputdata = new DataInputStream(inputfile);
while((strRead=inputdata.readLine())!=null){
StringTokenizer stUser = new StringTokenizer(strRead,"|");
if(stUser.nextToken().equals(name)){
return true;
}
}
}
catch(FileNotFoundException fn){
System.out.println("[ERROR] User File has not exist!"+fn);
out.println("warning|读写文件时出错!");
}
catch(IOException ie){
System.out.println("[ERROR] "+ie);
out.println("warning|读写文件时出错!");
}
return false;
}
private boolean isUserLogin(String name,String password){ //判断用户的用户名密码是否正确
String strRead;
try{
FileInputStream inputfile = new FileInputStream(USERLIST_FILE);
DataInputStream inputdata=new DataInputStream(inputfile);
while((strRead=inputdata.readLine())!=null){
if(strRead.equals(name+"|"+password)){
return true;
}
}
}
catch(FileNotFoundException fn){
System.out.println("[ERROR] User File has not exist!"+fn);
out.println("warning|读写文件时出错!");
}
catch(IOException ie){
System.out.println("[ERROR] "+ie);
out.println("warning|读写文件时出错!");
}
return false;
}
private void register() throws IOException{ // 用户注册
String name = st.nextToken(); //得到用户名称
String password = st.nextToken().trim();//得到用户密码
if(isExistUser(name)){
System.out.println("[ERROR] "+name+" Register fail!");
out.println("warning|该用户已存在,请改名!");
}
else{
RandomAccessFile userFile=new RandomAccessFile(USERLIST_FILE,"rw");
userFile.seek(userFile.length()); // 在文件尾部加入新用户信息
userFile.writeBytes(name+"|"+password+"\r\n");
longin(name); //自动登陆聊天室
}
}
private void login() throws IOException{ // 用户登陆(从登陆框直接登陆)
String name = st.nextToken(); //得到用户名称
String password = st.nextToken().trim();//得到用户密码
boolean succeed = false;
System.out.println("[USER LOGIN] "+name+":"+password+":"+socket);
for(int i=0;i<onlineUser.size();i++){
if(onlineUser.elementAt(i).equals(name)){
System.out.println("[ERROR] "+name+" is logined!");
out.println("warning|"+name+"已经登陆聊天室");
}
}
if(isUserLogin(name,password)){ // 判断用户名和密码
longin(name);
succeed = true;
}
if(!succeed){
out.println("warning|"+name+"登陆失败,请检查您的输入!");
System.out.println("[SYSTEM] "+name+" login fail!");
}
}
private void longin(String name) throws IOException{ // 用户登陆
out.println("login|succeed");
sendAll("online|"+name);
onlineUser.addElement(name);
socketUser.addElement(socket);
sendAll("talk|>>>欢迎 "+name+" 进来与我们一起交谈!");
System.out.println("[SYSTEM] "+name+" login succeed!");
}
private void talk() throws IOException{ // 聊天信息处理
String strTalkInfo = st.nextToken(); //得到聊天内容;
String strSender = st.nextToken(); //得到发消息人
String strReceiver = st.nextToken(); //得到接收人
System.out.println("[TALK_"+strReceiver+"] "+strTalkInfo);
Socket socketSend;
PrintWriter outSend;
// 得到当前时间
GregorianCalendar calendar = new GregorianCalendar();
String strTime="("+calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)+
":"+calendar.get(Calendar.SECOND)+")";
strTalkInfo +=strTime;
if(strReceiver.equals("All")){
sendAll("talk|"+strSender+" 对所有人说:"+strTalkInfo);
}
else{
if(strSender.equals(strReceiver)){
out.println("talk|>>>不能自言自语哦!");
}
else{
for(int i=0;i<onlineUser.size();i++){
if(strReceiver.equals(onlineUser.elementAt(i))){
socketSend = (Socket)socketUser.elementAt(i);
outSend = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socketSend.getOutputStream())),true);
outSend.println("talk|"+strSender+" 对你说:"+strTalkInfo);
}
else if(strSender.equals(onlineUser.elementAt(i))){
socketSend = (Socket)socketUser.elementAt(i);
outSend = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socketSend.getOutputStream())),true);
outSend.println("talk|你对 "+strReceiver+"说:"+strTalkInfo);
}
}
}
}
}
private void initClientOnline() throws IOException{ // 初始化在线用户列表
String strOnline = "online";
for(int i=0;i<onlineUser.size();i++){
strOnline += "|"+onlineUser.elementAt(i);
}
out.println(strOnline);
}
private void sendAll(String strSend){ // 信息群发
Socket socketSend;
PrintWriter outSend;
try{
for(int i=0;i<socketUser.size();i++){
socketSend = (Socket)socketUser.elementAt(i);
outSend = new PrintWriter(new BufferedWriter(new OutputStreamWriter
(socketSend.getOutputStream())),true);
outSend.println(strSend);
}
}
catch(IOException e){
System.out.println("[ERROR] send all fail!");
}
}
private String closeSocket(){ // 关闭套接字,并将用户信息从在线列表中删除
String strUser = "";
for(int i=0;i<socketUser.size();i++){
if(socket.equals((Socket)socketUser.elementAt(i))){
strUser = onlineUser.elementAt(i).toString();
socketUser.removeElementAt(i);
onlineUser.removeElementAt(i);
sendAll("remove|"+strUser);
}
}
try{
in.close();
out.close();
socket.close();
}catch(IOException e){
System.out.println("[ERROR] "+e);
}
return strUser;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -