📄 javachatcode.txt
字号:
public void actionPerformed(ActionEvent e) {
try {
String user,pass;
ServerIp=jt_servername.getText();
ServerPort=Integer.valueOf(jt_port.getText());
user=(String)comboUsername.getSelectedItem();
pass=txtPassword.getText();
if (connectserver(user,pass)==1) {
//将登陆成功的用户记入用户列表.
tr1.add(user);
write1 =new PrintWriter( new BufferedWriter(new FileWriter("manager.txt",false)));
Iterator it1;
it1=tr1.iterator();
while (it1.hasNext()){
write1.println(it1.next());
}
write1.close();
//打开聊天室界面并隐藏登陆界面.
lt1 = new liaotianshi(jt_port.getText()+"聊天室",user,sin,sout,"Manager",ServerIp,ServerPort);
lt1.pack();
setVisible(false);
lt1.setVisible(true);
lt1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginSucc=true;
System.out.println("登录成功!");
}
else {
loginSucc=false;
}
}
catch (IOException e2){
//System.out.println(e2.toString());
}
}
});
jbnButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//退出
if (loginSucc) {
sout.println("/logout");
sout.flush();
try{
sout.close();
clientSocket.close();
}catch (IOException dfe){
}
}
System.exit(0);
}
});
jbnButton1.setMnemonic(KeyEvent.VK_Y);
jbnButton2.setMnemonic(KeyEvent.VK_X);
// getContentPane().setLayout(new FlowLayout());
Insets is = new Insets(5,5,5,5);
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.anchor=GridBagConstraints.CENTER;
gBC.fill = GridBagConstraints.NONE;
gBC.gridx = 1;
gBC.gridy = 1;
gBC.gridwidth = 2;
gBC.gridheight=1;
gBC.insets=is;
getContentPane().add(lblname,gBC);
gBC.anchor=GridBagConstraints.CENTER;
gBC.fill = GridBagConstraints.NONE;
gBC.gridy = 2;
getContentPane().add(lblwelcome,gBC);
gBC.anchor=GridBagConstraints.WEST;
gBC.fill = GridBagConstraints.NONE;
gBC.gridx = 1;
gBC.gridy = 3;
gBC.gridwidth = 1;
gBC.gridheight=1;
gBC.insets=is;
getContentPane().add(lblUsername,gBC);
gBC.gridx = 1;
gBC.gridy = 4;
gBC.gridwidth = 1;
gBC.gridheight=1;
gBC.insets=is;
getContentPane().add(lblPassword,gBC);
gBC.gridx = 1;
gBC.gridy = 5;
getContentPane().add(lb_ServerName,gBC);
gBC.gridx = 2;
gBC.gridy = 5;
getContentPane().add(jt_servername,gBC);
gBC.gridx = 1;
gBC.gridy = 6;
getContentPane().add(lb_port,gBC);
gBC.gridx = 2;
gBC.gridy = 6;
getContentPane().add(jt_port,gBC);
gBC.anchor=GridBagConstraints.WEST;
gBC.fill = GridBagConstraints.HORIZONTAL;
gBC.gridx = 2;
gBC.gridy = 3;
gBC.gridwidth = 1;
gBC.gridheight=1;
gBC.insets=is;
getContentPane().add(comboUsername,gBC);
gBC.gridx = 2;
gBC.gridy = 4;
gBC.gridwidth = 1;
gBC.gridheight=1;
gBC.insets=is;
getContentPane().add(txtPassword,gBC);
JPanel jp1=new JPanel();
jp1.setLayout(new FlowLayout());
jp1.add(jbnButton1,gBC);
jp1.add(jbnButton2,gBC);
gBC.gridx = 1;
gBC.gridy = 7;
gBC.gridwidth = 2;
gBC.gridheight=1;
gBC.insets=new Insets(10,10,10,10);
getContentPane().add(jp1,gBC);
}
catch (IOException e){
System.out.println(e.toString());
}
}
public int connectserver(String username,String password){
String reply;
try {
clientSocket=new Socket(ServerIp, ServerPort);
sin = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sout = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
sout.println("login");
sout.flush();
sout.println(username);
sout.flush();
sout.println(password);
sout.
flush();
sout.println("Manager");
sout.flush();
reply=sin.readLine();
if (reply.equals("login succ") )
return 1;
else if (reply.equals("same user login")){
JOptionPane.showMessageDialog(null, "登录失败(该用户名已经被占用)");
return 0;
}
else{
JOptionPane.showMessageDialog(null, "登录失败(原因:错误的用户名或密码)");
return 0;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "无法连接到服务器!");
}
return 0;
}
public static void main(String[] args) {
manager frm = new manager("登陆界面");
frm.pack();
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
服务端类:
package chatroom;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.Iterator;
import java.util.Vector;
import java.util.Date;
import javax.swing.*;
public class Server extends JFrame {
static Vector srv_userlist=new Vector();
static String logFile = "log.txt";
ServerSocket serverSocket;
PrintWriter log;
JButton jb_start,jb_stop;
JLabel message,jl_port;
JTextField jf_port;
ServerThread srv_thread;
static String serverName;
static String portNumber;
static String databaseName;
static String userName;
static String password;
// public static void initAuthFile() throws Exception {
// String ups[] = new String[] {"hackgun", "1234", "Wakao", "1234","lala0","1234"};
// DataOutputStream dos = new DataOutputStream(new FileOutputStream(authFile));
// for (int i = 0; i < ups.length; i++) {
// dos.writeUTF(ups[i]);
// }
// dos.close();
// }
public Server(){
super("聊天室服务");
if (read_ini()==false) {
JOptionPane.showMessageDialog(null, "ini文件读入错误,请检查!");
System.exit(0);
}
try{
log = new PrintWriter(new FileWriter(new File(logFile), true));
}catch (Exception e) {
e.printStackTrace();
}
jf_port=new JTextField("10001");
jb_start=new JButton("开启服务");
jb_stop=new JButton("停止服务");
message=new JLabel("聊天室服务 ");
jl_port=new JLabel("端口号 ");
GridBagConstraints gBC = new GridBagConstraints();
Insets is = new Insets(5,5,5,5);
Container thisCP;
thisCP=getContentPane();
thisCP.setLayout(new GridBagLayout());
gBC.anchor=GridBagConstraints.CENTER;
gBC.fill = GridBagConstraints.NONE;
gBC.gridwidth = 2;
gBC.gridheight=1;
gBC.insets=is;
gBC.gridy = 1;
gBC.gridx = 1;
thisCP.add(message,gBC);
gBC.gridy = 2;
gBC.gridx = 1;
gBC.gridwidth = 1;
gBC.anchor=GridBagConstraints.EAST;
thisCP.add(jl_port,gBC);
gBC.anchor=GridBagConstraints.WEST;
gBC.gridx = 2;
thisCP.add(jf_port,gBC);
gBC.gridy = 3;
gBC.gridx = 1;
thisCP.add(jb_start,gBC);
gBC.gridx = 2;
thisCP.add(jb_stop,gBC);
this.setSize(200, 150);
this.setVisible(true);
jb_stop.setEnabled(false);
jb_start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//
startServer();
}
});
jb_stop.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//
stopServer();
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
stopServer();
log.println((new Date()).toString()+" server close");
log.flush();
log.close();
} catch (Exception e2) {
e2.printStackTrace();
}
System.exit(0);
}
});
startServer();
}
public void startServer(){
srv_thread=new ServerThread(this);
}
public void stopServer(){
try{
PrintWriter sout_2;
Socket socket_2;
ClientThread ct;
for (int i = 0; i < Server.srv_userlist.size(); i++){
socket_2 = ((server_user_ob) Server.srv_userlist.elementAt(i)).getSocket();
sout_2 = new PrintWriter(new OutputStreamWriter(socket_2.getOutputStream()));
ct=((server_user_ob) Server.srv_userlist.elementAt(i)).getClientThread();
sout_2.println("/TALK");
sout_2.println("系统\n对\n所有人\n说:\n服务器因故停止服务...");
sout_2.println("TALK/");
sout_2.println("STOP_SERVER/");
sout_2.flush();
sout_2.close();
socket_2.close();
ct.stop();
}
srv_userlist.clear();
serverSocket.close();
message.setText("聊天室终止服务");
jb_start.setEnabled(true);
jb_stop.setEnabled(false);
log.println((new Date()).toString()+" server close");
}catch (IOException eE){
System.out.println("出错了");
}
}
public boolean read_ini(){
BufferedReader read;
String s;
try{
read = new BufferedReader(new FileReader("db_ini.txt"));
if ((s = read.readLine()) != null){
serverName=s;
}else return false;
if ((s = read.readLine()) != null){
portNumber=s;
}else return false;
if ((s = read.readLine()) != null){
databaseName=s;
}else return false;
if ((s = read.readLine()) != null){
userName=s;
}else return false;
if ((s = read.readLine()) != null){
password=s;
}else return false;
read.close();
}catch (IOException e){
//
}
return true;
}
public static void main(String[] args) {
Server sr = new Server();
}
}
class ServerThread extends Thread{
Server Srv;
boolean starserver=false;
public ServerThread(Server asrv_main){
Srv=asrv_main;
this.start();
}
public void run(){
try {
Srv.serverSocket = new ServerSocket(Integer.valueOf(Srv.jf_port.getText()));
starserver=true;
Srv.message.setText("聊天室服务开启中...");
Srv.jb_start.setEnabled(false);
Srv.jb_stop.setEnabled(true);
Srv.log.println((new Date()).toString()+" server start");
Srv.log.flush();
while (true) {
Socket clientSocket = Srv.serverSocket.accept();
ClientThread ct = new ClientThread(clientSocket,Srv.log);
}
} catch (Exception e) {
if (starserver==false){
JOptionPane.showMessageDialog(null, "端口号已经被占用");
}
else{
Srv.log.println((new Date()).toString()+" server close unexpectly");
Srv.log.flush();
}
starserver=false;
//e.printStackTrace();
}
}
}
class ClientThread extends Thread {
Vector sline=new Vector();
boolean LoginSucc=false;
String user;
//Socket socket;
server_user_ob srv_user_ob;
BufferedReader sin;
PrintWriter sout;
PrintWriter log;
public ClientThread(Socket client,PrintWriter logs) {
try {
sin = new BufferedReader(new InputStreamReader(client
.getInputStream()));
sout = new PrintWriter(new OutputStreamWriter(client
.getOutputStream()));
log = logs;
} catch (IOException e) {
e.printStackTrace();
System.out.println("connection break");
log.println((new Date()).toString()+"connection break");
log.flush();
close();
return;
}
srv_user_ob=new server_user_ob(client,"","",this);
this.start();
}
public ClientThread getClientThread() {
return null;
}
public void close() {
try {
sin.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
sout.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (LoginSucc){
Server.srv_userlist.removeElement(srv_user_ob);
sendmsgtoall("/RefreshUserList","所有人");
sendmsgtoall("/lessuser","所有人");
log.println((new Date()).toString()+" "+srv_user_ob.getUsername()+" connection break");
log.flush();
}
srv_user_ob.getSocket().close();
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void sendmsgtoall(String msg,String who){
PrintWriter sout_2;
Socket socket_2;
try{
if (msg.equals("/RefreshUserList")){
for (int i = 0; i < Server.srv_userlist.size(); i++){
socket_2 = ((server_user_ob) Server.srv_userlist.elementAt(i)).getSocket();
sout_2 = new PrintWriter(new OutputStreamWriter(socket_2.getOutputStream()));
sout_2.println("/RefreshUserList");
for (int i2 = 0; i2 < Server.srv_userlist.size(); i2++){
sout_2.println(((server_user_ob)Server.srv_userlist.elementAt(i2)).getUsername());
sout_2.println(((server_user_ob)Server.srv_userlist.elementAt(i2)).getNickname());
}
sout_2.println("SendUserList/");
sout_2.flush();
}
}
else if(msg.equals("/TALK")){
insertmsg(1);
for (int i = 0; i < Server.srv_userlist.size(); i++){
socket_2 = ((server_user_ob) Server.srv_userlist.elementAt(i)).getSocket();
sout_2 = new PrintWriter(new OutputStreamWriter(socket_2.getOutputStream()));
sout_2.println("/TALK");
for (int i2 = 0; i2 < sline.size(); i2++){
sout_2.println((String) sline.elementAt(i2));
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -