?? server.java
字號:
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server{
ServerSocket serverSocket; // 創(chuàng)建服務器端套接字
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){ // 監(jiān)聽客戶端的連接請求,并返回客戶端socket
Socket socket=serverSocket.accept();
new ServerThread(socket); // 創(chuàng)建一個新線程來處理與該客戶的通訊
}
}
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發(fā)來的信息后進行解析、處理、轉(zhuǎn)發(fā)。
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){ //從服務器端接收一條信息后拆分、解析,并執(zhí)行相應操作
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+"已經(jīng)登陸聊天室");
}
}
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(); //得到聊天內(nèi)容;
String strSender = st.nextToken(); //得到發(fā)消息人
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){ // 信息群發(fā)
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 + -