/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package client;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
/**
*
* @author ch
*/
public class MainFrame extends javax.swing.JFrame {
Socket socket;
BufferedReader sin;
PrintWriter sout;
boolean closed=false;
DefaultListModel dlm=new DefaultListModel();
DefaultListModel fileDlm = new DefaultListModel();
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
userList.setModel(dlm);
jFileList.setModel(fileDlm);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jtServerIP = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jtServerPort = new javax.swing.JTextField();
btnConnect = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jtMessage = new javax.swing.JTextArea();
jLabel3 = new javax.swing.JLabel();
jSendMessage = new javax.swing.JTextField();
btnSend = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jtUsername = new javax.swing.JTextField();
CServer = new javax.swing.JCheckBox();
groupCb = new javax.swing.JCheckBox();
btnUpload = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jScrollPane2 = new javax.swing.JScrollPane();
userList = new javax.swing.JList();
jScrollPane3 = new javax.swing.JScrollPane();
jFileList = new javax.swing.JList<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabel1.setText("服務器 IP:");
jtServerIP.setText("127.0.0.1");
jLabel2.setText("端口號:");
btnConnect.setText("登錄");
btnConnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConnectActionPerformed(evt);
}
});
jtMessage.setColumns(20);
jtMessage.setRows(5);
jScrollPane1.setViewportView(jtMessage);
jLabel3.setText("消息:");
btnSend.setText("發送");
btnSend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSendActionPerformed(evt);
}
});
jLabel4.setText("用戶名:");
CServer.setText("服務器");
groupCb.setText("羣發");
btnUpload.setText("上傳文件");
btnUpload.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUploadActionPerformed(evt);
}
});
jButton1.setText("下載文件");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
userList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(userList);
jTabbedPane1.addTab("在線用戶", jScrollPane2);
jFileList.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jFileList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jFileListValueChanged(evt);
}
});
jScrollPane3.setViewportView(jFileList);
jTabbedPane1.addTab("可用文件", jScrollPane3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jtServerIP, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jtServerPort, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
.addGap(22, 22, 22)
.addComponent(btnConnect)
.addGap(76, 76, 76))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1)
.addGap(30, 30, 30)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25))))
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(CServer)
.addGap(18, 18, 18)
.addComponent(groupCb)
.addGap(141, 141, 141)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(btnUpload))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSendMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnSend)
.addGap(5, 5, 5)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jtServerIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jtServerPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnConnect)
.addComponent(jLabel4)
.addComponent(jtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jSendMessage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSend))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CServer)
.addComponent(groupCb))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnUpload)
.addComponent(jButton1)))
.addContainerGap(63, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String serverIP=this.jtServerIP.getText();
int port =Integer.parseInt(this.jtServerPort.getText());
try {
socket=new Socket(serverIP,port);
sin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
sout=new PrintWriter(socket.getOutputStream());
jtMessage.setText("服務器連接成功。\n");
sout.println("login,"+jtUsername.getText());
sout.flush();
new Thread(){
public void run()
{
while(true)
{
try {
String message=sin.readLine();
/*login,username:該username用戶在線,將其添加到用戶列表
logout,username;該客戶下線,從用戶列表中刪除
message,消息:服務器消息,直接顯示
talk,接受者,發送者,消息:解析出發送者的名字和消息,顯示在消息列表中*/
if("logout".equals(message))
{
break;
}
String mess[]=message.split(",");
switch (mess[0]) {
case "login":
dlm.addElement(mess[1]);
break;
case "logout":
dlm.removeElement(mess[1]);
break;
case "message":
jtMessage.append("服務器發送來的消息:" + message.substring(8) + "\n");
break;
case "talk":
String sender = mess[2];
String temp = message.substring(7 + mess[1].length() + mess[2].length());
jtMessage.append(sender + ":" + temp + "\n");
break;
case "group":
String msgSender = mess[1];
jtMessage.append(msgSender + "發送的羣發消息:" + mess[2] + "\n");
break;
case "filelist":
for(int i = 1; i < mess.length; i++) {
fileDlm.addElement(mess[i]);
}
jTabbedPane1.setSelectedIndex(1);
default:
}
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}.start();
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(this.CServer.isSelected()){
sout.println("message,"+jSendMessage.getText());
sout.flush();
jtMessage.append("發送給服務器消息:"+jSendMessage.getText()+"\n");
}
else
{
if (this.groupCb.isSelected()) {
String sendString = "group," + jtUsername.getText() + "," + jSendMessage.getText();
sout.println(sendString);
sout.flush();
jtMessage.append("你發送的羣發消息:" + jSendMessage.getText() + "\n");
jSendMessage.setText("");
return;
};
if(userList.getSelectedIndex()<0) {
// String sendString = "group," + jtUsername.getText() + "," + jSendMessage.getText();
// sout.println(sendString);
// sout.flush();
// jtMessage.append("你發送的羣發消息:" + jSendMessage.getText() + "\n");
// jSendMessage.setText("");
return;
};
String receiver=userList.getSelectedValue().toString();
String sendString="talk,"+receiver+","+jtUsername.getText()+","+jSendMessage.getText();
sout.println(sendString);
sout.flush();
jtMessage.append("發送給"+receiver+"消息:"+jSendMessage.getText()+"\n");
}
jSendMessage.setText("");
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {
try {
// TODO add your handling code here:
sout.println("logout");
sout.flush();
sin.close();
sout.close();
socket.close();;
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnUploadActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("選擇文件");
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
final File src = jfc.getSelectedFile();
sout.println("upload," + src.getName());
sout.flush();
new Thread() {
public void run() {
try {
Socket s = new Socket(jtServerIP.getText(), 10056);
long fileLength = src.length();
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeLong(fileLength);
FileInputStream fis = new FileInputStream(src);
byte[] buffer = new byte[1024];
int length = fis.read(buffer);
while (length > 0) {
dos.write(buffer, 0, length);
dos.flush();
length = fis.read(buffer);
}
fis.close();
dos.close();
s.close();
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
btnUpload.setEnabled(true);
}
}.start();
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
sout.println("download1");
sout.flush();
}
private void jFileListValueChanged(javax.swing.event.ListSelectionEvent evt) {
// TODO add your handling code here:
sout.println("download2," + jFileList.getSelectedValue().toString());
sout.flush();
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("下載文件");
int result = jfc.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
sout.println("download2," + jFileList.getSelectedValue().toString());
sout.flush();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JCheckBox CServer;
private javax.swing.JButton btnConnect;
private javax.swing.JButton btnSend;
private javax.swing.JButton btnUpload;
private javax.swing.JCheckBox groupCb;
private javax.swing.JButton jButton1;
private javax.swing.JList<String> jFileList;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextField jSendMessage;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTextArea jtMessage;
private javax.swing.JTextField jtServerIP;
private javax.swing.JTextField jtServerPort;
private javax.swing.JTextField jtUsername;
private javax.swing.JList userList;
// End of variables declaration
}