Beruflich Dokumente
Kultur Dokumente
Cu 1:
TimeServer.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Server;
public static void main(String[] args) throws Exception { ServerSocket server = new ServerSocket(7000); System.out.println("Server is started"); while (true) {
Socket socket = server.accept(); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); String time = new Date().toString(); dos.writeUTF("Server tra lai ngay gio=" + time); socket.close(); } } }
TimeClient.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Client;
public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 7000); DataInputStream din = new DataInputStream(socket.getInputStream()); String time = din.readUTF(); System.out.println(time); } } Demo:
Cu 2:
TimeServer.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Server;
public static void main(String[] args) throws Exception { ServerSocket server = new ServerSocket(port); System.out.println("Server is started"); Socket socket ; while (true) {
} }
TimeClient.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Client;
/**
* * @author congthanh */ import java.io.DataInputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger;
public static void main(String[] args) throws Exception { Thread th=new Thread(); th.start(); while (true) { try { th.sleep(1000); Socket socket = new Socket("localhost", 7000); DataInputStream din = new DataInputStream(socket.getInputStream()); String time = din.readUTF(); System.out.println(time); } catch (UnknownHostException ex) { Logger.getLogger(TimeClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) {
DoConn.java: (package Server) /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Server;
import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger;
/** * * @author congthanh */ public class DoConn implements Runnable{ private Socket msocket;
public void run(){ DataOutputStream dos = null; try { dos = new DataOutputStream(this.msocket.getOutputStream()); String time = new Date().toString(); dos.writeUTF("Server tra lai ngay gio=" + time); } catch (IOException ex) { Logger.getLogger(DoConn.class.getName()).log(Level.SEVERE, null, ex); } finally { try { this.msocket.close(); dos.close(); } catch (IOException ex) { Logger.getLogger(DoConn.class.getName()).log(Level.SEVERE, null, ex); } } }
Cu 3: Server: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Server; Server.java
public static void main(String[] args) throws Exception { ServerSocket server = new ServerSocket(port); System.out.println("Server is started"); Socket socket ; while (true) {
socket= server.accept(); DoConn mconn=new DoConn(socket); Thread t=new Thread(mconn); t.start(); // // System.out.println("Khoi tao Thread: "+t.getName()); System.out.println("Tong so Thread: "+Thread.activeCount()); //System.out.println(mconn); // // // // } DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); String time = new Date().toString(); dos.writeUTF("Server tra lai ngay gio=" + time); socket.close();
} } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Server; DoConn.java
import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger;
private BufferedReader din = null; private DataOutputStream dos = null; //DataInputStream din = null; public DoConn(Socket msocket) { this.msocket = msocket; }
// // //
try { dos = new DataOutputStream(this.msocket.getOutputStream()); din = new BufferedReader(new InputStreamReader( msocket.getInputStream())); // // // din = new DataInputStream(this.msocket.getInputStream()); //String time = new Date().toString(); country = din.readUTF(); String time = mTimeZone(din.readLine()); //System.out.print(time); dos.writeUTF(time);
} catch (IOException ex) { Logger.getLogger(DoConn.class.getName()).log(Level.SEVERE, null, ex); } finally { try { this.msocket.close(); dos.close(); } catch (IOException ex) {
// Calendar mCalendar=Calendar.getInstance(TimeZone.getTimeZone("Pacific/Fiji")); // String mTime=mCalendar.get(Calendar.HOUR)+ ":" + mCalendar.get(Calendar.MINUTE) + ":" + mCalendar.get(Calendar.SECOND); Date date = new Date(); //System.out.println(country); DateFormat firstFormat = new SimpleDateFormat("HH:mm:ss"); TimeZone firstTime = TimeZone.getTimeZone(country.toString()); firstFormat.setTimeZone(firstTime);
Client.java /*
* To change this template, choose Tools | Templates * and open the template in the editor. */ package Client;
/** * * @author congthanh */ import java.io.DataInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger;
public static void main(String[] args) throws Exception { Thread th=new Thread(); th.start(); ClientJFrame jf1=new ClientJFrame(); jf1.setVisible(true);
Socket socket=null; // BufferedReader in = null; PrintWriter out = null; DataInputStream din=null; while (true) { try { th.sleep(1000); socket = new Socket("localhost", 7000); ///BufferedReader // // // in = new BufferedReader(new InputStreamReader( socket.getInputStream())); String time = in.readLine(); //PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println(country);
//System.out.print(time); jf1.mSetTime(time);
// // //
} catch (UnknownHostException ex) { Logger.getLogger(TimeClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(TimeClient.class.getName()).log(Level.SEVERE, null, ex); } } } }
ClientJFrame.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Client;
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException;
import java.text.DateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger;
public ClientJFrame() { initComponents(); String[] timeZoneIDList = TimeZone.getAvailableIDs(); for (String timeZoneID : timeZoneIDList) { jComboBox1.addItem(timeZoneID);
} jComboBox1.setSelectedItem(TimeClient.country);
/** * 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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] {})); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } });
jTextField1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jTextField1.setText("fdf"); jTextField1.setMargin(new java.awt.Insets(0, 200, 0, 0)); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } });
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(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.L EADING) .addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 500, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.B ASELINE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(79, Short.MAX_VALUE)) );
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // // //// //// //// //// //// // // // // // //// //// //// //// //// ex); //// // } TimeClient.country=(String) jComboBox1.getSelectedItem(); } socket = new Socket("localhost", 7000); out = new PrintWriter(socket.getOutputStream(), true); out.println(jComboBox1.getSelectedItem()); out.close(); socket.close(); } catch (UnknownHostException ex) { Logger.getLogger(ClientJFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ClientJFrame.class.getName()).log(Level.SEVERE, null, ex); }finally{ out.close(); try { socket.close(); } catch (IOException ex) { Logger.getLogger(ClientJFrame.class.getName()).log(Level.SEVERE, null, try {
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }
/** * @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(ClientJFrame.class.getName()).log(java.util.lo gging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.lo gging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.lo gging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.lo gging.Level.SEVERE, null, ex); } //</editor-fold>
public void mSetTime(String time) { //DateFormat styleDate = DateFormat.getTimeInstance(DateFormat.FULL, Locale.UK); //SimpleDateFormat ft = new SimpleDateFormat ("HH:mm:ss"); //String mtime = styleDate.format(time); jTextField1.setText(time); //System.out.print(time); repaint(); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JComboBox jComboBox1; private javax.swing.JTextField jTextField1; // End of variables declaration }
Cu 5: Server.
o
Bai5Server.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Server;
public static void main(String[] args) throws Exception { ServerSocket server = new ServerSocket(port); System.out.println("Server is started"); Socket socket ; while (true) {
Thread t=new Thread(mconn); t.start(); // // System.out.println("Khoi tao Thread: "+t.getName()); System.out.println("Tong so Thread: "+Thread.activeCount()); //System.out.println(mconn); // DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); // // // } String time = new Date().toString(); dos.writeUTF("Server tra lai ngay gio=" + time); socket.close();
} }
o
Bai5Do.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Server;
import java.util.logging.Logger;
private Socket mSocket; private String FileName = "File.txt"; private double so1, so2; private boolean replay = true; DataOutputStream dos = null; DataInputStream din = null;
public void run() { try { String st = null; dos = new DataOutputStream(mSocket.getOutputStream()); din = new DataInputStream(mSocket.getInputStream());
so1 = Double.parseDouble(mRead(dos, din, 1)); //System.out.println(so1); so2 = Double.parseDouble(mRead(dos, din, 2)); //System.out.println(so2); char pheptoan = mRead(dos, din, 3).charAt(0); //System.out.println(pheptoan); String kq = "Ket qua: " + so1 + pheptoan + so2 + "=" + (mOperator(so1, so2, pheptoan)).toString(); dos.writeUTF(kq); mWriteFile(kq); dos.flush(); String s=din.readUTF(); replay = Boolean.parseBoolean(s); } catch (IOException ex) { Logger.getLogger(Bai5Do.class.getName()).log(Level.SEVERE, null, ex); } } dos.close(); din.close(); mSocket.close(); } catch (IOException ex) {
public String mRead(DataOutputStream dos, DataInputStream din, Integer i) { try { if (i == 3) { dos.writeUTF("Nhap phep toan: "); } else { dos.writeUTF("Nhap so thu " + i + ": "); } dos.flush(); String st = din.readUTF(); return st; } catch (IOException ex) { Logger.getLogger(Bai5Do.class.getName()).log(Level.SEVERE, null, ex); return ""; } }
public Double mOperator(Double so1, Double so2, char str) { Double kq = 0.0; switch (str) {
case '+': kq = so1 + so2; break; case '-': kq = so1 - so2; break; case '*': kq = so1 * so2; break; case '/': kq = so1 / so2; break; default: kq = 0.0; break; } return kq; }
public void mWriteFile(String str) throws IOException { FileReader inputFileReader = null; FileWriter outputFileReader = null;
try { //Read File inputFileReader = new FileReader(FileName); BufferedReader inputStream = new BufferedReader(inputFileReader); String inLine = null; while ((inLine = inputStream.readLine()) != null) { strBuffers.append(inLine + "\r\n"); } strBuffers.append(str); inputStream.close(); //writeFile outputFileReader = new FileWriter(FileName); PrintWriter outputStream = new PrintWriter(outputFileReader); outputStream.println(strBuffers); outputStream.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Bai5Do.class.getName()).log(Level.SEVERE, null, ex); } } } Client
o
/** * * @author congthanh */ import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; import java.util.Scanner; /* * Chuong trinh chat don gian Cient nhan chuoi tu ban phim gui den server Nhan * du lieu tu server */
public static void main(String[] args) throws Exception { Socket socket = new Socket("localhost", 7000); boolean replay = true; while (replay) {//true. false //Socket
DataInputStream din = new DataInputStream(socket.getInputStream());//nhan DataOutputStream dos = new DataOutputStream(socket.getOutputStream());//gui //nhap chuoi de gui den sever Scanner kb = new Scanner(System.in);//lop de nhap du lieu tu ban phim for (int i = 0; i < 3; i++) { String st = din.readUTF(); System.out.print(st); String msg = kb.nextLine(); //nhap dos.writeUTF(msg); dos.flush(); } String st = din.readUTF(); System.out.println(st); //replay System.out.print("Ban muon tiep tuc ('Y'/'N'): "); char msg = kb.nextLine().charAt(0); switch (msg) { case 'Y': case 'y': dos.writeUTF("true"); dos.flush(); break; default: dos.writeUTF("false");
} socket.close(); } }
Cu 6: Server: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai6Server; StartServer.java
import java.net.Socket;
public static void main(String[] args) { try { Server mServer = new Server(); if (mServer.StartServer(7000)) { System.out.println("Start Server thanh cong");
int i = 0; while (true) { mSocket = null; mSocket = mServer.ListterConnect(); if (mSocket != null) { // Tao 1 doi tuong con de Run Connect - Dung MutiThread String key="Client:" + (i++); DoServer mDo = new DoServer(mSocket,key ); Server.AddConnect(key, mDo); Thread th=new Thread(mDo); th.start(); //System.out.print("Client:" + (++i)); } else { //System.out.println("Ket noi Server Database That bai ");
} }
Server.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai6Server;
public boolean StartServer(int port) { try { if (mServerSocket == null) { mServerSocket = new ServerSocket(port); return true; } else { System.err.println("Server da start truoc do"); return false; }
} }
public Socket ListterConnect() { try { return mServerSocket.accept(); } catch (Exception e) { return null; } }
public static void SendtoClient(String str, boolean listaccount) { try { String msg=null; if (listaccount) {//send to client the list account //--------msg="0,"+str; //0 la ma de client nhan dien danh sach acc count va msg } else { //send to client the msg //---------msg="1,"+str; //1 la ma de client nhan dien danh sach acc count va msg } Enumeration names = mHashtable.keys(); String mkey=null; while (names.hasMoreElements()) { mkey = (String) names.nextElement();
DoServer mDo = (DoServer) mHashtable.get(mkey); mDo.SendtoClient(msg); } } catch (Exception e) { System.err.println("Error: Send to Client"); } }
public static void CloseConnect(String key) { mHashtable.remove(key); //Remove user ListAcount } public static void AddConnect(String key,DoServer value){ mHashtable.put(key, value); }
DoServer.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai6Server;
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.sql.ResultSet; import java.util.logging.Level; import java.util.logging.Logger;
private Socket mSocket; private DataInputStream din; private DataOutputStream dos; private String key; //Data private ResultSet mRs; //User protected static StringBuffer mListAccount; private String mFullName, user;
static {
public DoServer(Socket mSocket, String key) { try { this.mSocket = mSocket; this.key = key; user = key; this.din = new DataInputStream(mSocket.getInputStream()); this.dos = new DataOutputStream(mSocket.getOutputStream());
@Override public void run() { if (CheckLogin()) { //login thanh cong SendtoClient("true," + mFullName); Server.SendtoClient("He thong:," + user + " da tham gia Room", false); Server.SendtoClient(mListAccount.toString(), true); //Send listAccount to AllClient ReceiveClient();
public void ReceiveClient() { try { while (true) { //Read data tu client String[] tmp = ReadClient(); if ("close".equals(tmp[0])) { //Remove listAccount Server.CloseConnect(key); //Remove user in HasTable Server.SendtoClient("He thong:: " + tmp[1] + " da thoat Room", false); } else { System.out.print(tmp[0] + "." + tmp[1]); Server.SendtoClient(tmp[0] + "," + tmp[1], false); }
} } catch (Exception e) { } }
String[] tmp = ReadClient(); String user, pass; user = tmp[0]; pass = tmp[1]; this.user = user; //System.out.println(user +","+ pass); if (!user.isEmpty() && !pass.isEmpty()) { // dieu kien login String sql = "SELECT * FROM Account where username='" + user + "' and passwork='" + pass + "'";//SQL - SELECT ACCOUNT //mRs = mData.ExecuteSelectDB(sql); // if //(mRs.next()) { //Login thanh cong //lay thong tin tai khoan mListAccount.append(user + ","); // mFullName = mRs.getString("fullname"); return true; //login thanh cong } else {
private String[] ReadClient() { String[] temp = null; try { String in = din.readUTF(); //System.out.print(in); if (!in.isEmpty()) { temp = in.split(","); } } catch (Exception e) { System.err.println("ERROR : ReadClient"); Server.CloseConnect(key); Server.SendtoClient("He thong:," + user + " da thoat khoi Room", false); } return temp; } } Client:
-
import java.awt.event.KeyEvent;
Client mClient;
/** * 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.
jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel();
jTextField1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextField1KeyPressed(evt); }
});
jButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton1.setText("Exit"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } });
jButton2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton2.setText("Login"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } });
jButton3.setText("Create");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton3) .addGap(0, 210, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement .RELATED) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(52, 52, 52) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement .RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(86, 86, 86)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(27, 27, 27) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.BASELINE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELAT ED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNREL ATED) .addComponent(jButton3) .addGap(26, 26, 26)) );
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: mClient = new Client();
if (mClient.ConnectServer("localhost", 7000)) { String user = jTextField1.getText(); if (!user.isEmpty() ) { if (mClient.Login(user, "nopass")) { MClient mMClient = new MClient(); mMClient.setmClient(mClient); mMClient.RunMsgMain(mClient.getDin()); mMClient.setVisible(true); this.setVisible(false); } else { //Sai ten dang nhap hoac pass jLabel3.setText("Sai ten dang nhap hoac mat khau"); } } else { //Nhap day du user and pass jLabel3.setText("Nhap day du User and Pass"); } } else { //Server khong hoat dong jLabel3.setText("Sory! Server tam ngung hoat dong"); }
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: System.exit(0); }
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if(evt.getKeyCode()==KeyEvent.VK_ENTER){ jButton2ActionPerformed(null); } }
/** * @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(MLogin.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MLogin.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MLogin.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MLogin.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex);
} //</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
} }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JTextField jTextField1; // End of variables declaration }
MClient.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai6Client;
public void RunMsgMain(DataInputStream din) { InClient mIn = new InClient(din); Thread th1 = new Thread(mIn); th1.start(); }
/** * 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">
jScrollPane1 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(jList1);
jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton1.setText("Send"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); }
});
jTextArea2.setColumns(20); jTextArea2.setRows(1); jTextArea2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextArea2KeyPressed(evt); } }); jScrollPane4.setViewportView(jTextArea2);
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RE LATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement .RELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane3))) .addGroup(layout.createSequentialGroup() .addGap(122, 122, 122)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELAT ED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RE LATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.LEADING)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: try { String str = jTextArea2.getText().trim(); if (!str.equals("")) { String str2 = mClient.getUser() + "," + str; mClient.getDos().writeUTF(str2); jTextArea2.setText(""); } } catch (Exception e) { //err } }
private void jTextArea2KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if(evt.getKeyCode()==KeyEvent.VK_ENTER){
jButton1ActionPerformed(null); } }
/** * @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(MClient.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MClient.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MClient.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MClient.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } //</editor-fold>
public void run() { new MClient().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JList jList1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextArea jTextArea2; // End of variables declaration
try { while (true) { String in = din.readUTF(); if (!in.isEmpty()) { temp = in.split(","); // xu ly khi nhan duoc du lieu if ("0".equals(temp[0])) { //setList Account String[] tmp = new String[temp.length - 1]; for (int i = 1; i < temp.length; i++) { tmp[i - 1] = temp[i]; } //set List account cho Client; jList1.setListData(tmp); } else { // Set Msgbox jTextArea1.append(temp[1] + ":" + temp[2] + "\n"); } } } } catch (Exception e) { System.err.println("ERROR : ReadClient"); } } }
} Client /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai6Client;
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger;
//user private String user; private String pass; private String fullname;
public Client() { }
public boolean ConnectServer(String ip, int port) { try { mSocket = new Socket("localhost", 7000); dos = new DataOutputStream(mSocket.getOutputStream());
public boolean Login(String user, String pass) { try { this.user=user; if (!user.isEmpty() && !pass.isEmpty()) { if (mSocket != null) { dos.writeUTF(user + "," + pass); //Send User And Passwork String in = din.readUTF(); if (!in.isEmpty()) { String[] temp ; temp = in.split(","); if (Boolean.parseBoolean(temp[0])) { //login true fullname = temp[1]; return true; } } } } } catch (IOException ex) { // Read respone cua server
Cu 7: Server
-
Tch hp Driver SQL: sqljdbc4.jar StartServer.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7Server;
import java.net.Socket;
public static void main(String[] args) { try { Server mServer = new Server(); ConnectData mData = new ConnectData(); if (mServer.StartServer(7000)) { System.out.println("Start Server thanh cong"); if (mData.ConnectDB()) { System.out.println("Ket noi Server DataBase Thanh Cong"); int i = 0; while (true) { mSocket = null; mSocket = mServer.ListterConnect(); if (mSocket != null) { // Tao 1 doi tuong con de Run Connect - Dung MutiThread String key="Client:" + (i++); DoServer mDo = new DoServer(mSocket,key , mData); Server.AddConnect(key, mDo); Thread th=new Thread(mDo); th.start(); //System.out.print("Client:" + (++i)); } else { //System.out.println("Ket noi Server Database That bai "); }
} }else { System.out.print("Start Server Database that bai"); } } else { System.out.print("Start Server that bai"); } } catch (Exception e) { } } } Server.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7Server;
/** *
//set and get properties static{ mHashtable = new Hashtable(); } public Server() { }
public boolean StartServer(int port) { try { if (mServerSocket == null) { mServerSocket = new ServerSocket(port); return true; } else { System.err.println("Server da start truoc do"); return false; }
public Socket ListterConnect() { try { return mServerSocket.accept(); } catch (Exception e) { return null; } }
public static void SendtoClient(String str, boolean listaccount) { try { String msg=null; if (listaccount) {//send to client the list account //--------msg="0,"+str; //0 la ma de client nhan dien danh sach acc count va msg } else { //send to client the msg //---------msg="1,"+str; //1 la ma de client nhan dien danh sach acc count va msg } Enumeration names = mHashtable.keys();
String mkey=null; while (names.hasMoreElements()) { mkey = (String) names.nextElement(); DoServer mDo = (DoServer) mHashtable.get(mkey); mDo.SendtoClient(msg); } } catch (Exception e) { System.err.println("Error: Send to Client"); } }
public static void CloseConnect(String key) { mHashtable.remove(key); //Remove user ListAcount } public static void AddConnect(String key,DoServer value){ mHashtable.put(key, value); }
public void StopServer() { } } DoServer.java /* * To change this template, choose Tools | Templates * and open the template in the editor.
*/ package Bai7Server;
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.midi.SysexMessage;
private Socket mSocket; private DataInputStream din; private DataOutputStream dos; private String key; //Data private ConnectData mData;
private ResultSet mRs; //User protected static StringBuffer mListAccount; private String mFullName, user; static{ mListAccount = new StringBuffer(); } public DoServer(Socket mSocket, String key, ConnectData mData) { try { this.mSocket = mSocket; this.key = key; this.mData = mData; this.din = new DataInputStream(mSocket.getInputStream()); this.dos = new DataOutputStream(mSocket.getOutputStream());
@Override public void run() { if (CheckLogin()) { //login thanh cong SendtoClient("true," + mFullName); Server.SendtoClient("He thong:," + user + " da tham gia Room", false);
public void ReceiveClient() { try { while (true) { //Read data tu client String[] tmp = ReadClient(); if ("close".equals(tmp[0])) { //Remove listAccount Server.CloseConnect(key); //Remove user in HasTable Server.SendtoClient("He thong:: " + tmp[1] + " da thoat Room", false); } else {System.out.print(tmp[0] + "."+ tmp[1]); Server.SendtoClient(tmp[0] +","+ tmp[1], false); }
} } catch (Exception e) { }
public void SendtoClient(String str) { try { dos.writeUTF(str); } catch (IOException ex) { Logger.getLogger(DoServer.class.getName()).log(Level.SEVERE, null, ex); } }
private boolean CheckLogin() { try { String[] tmp = ReadClient(); String user, pass; user = tmp[0]; pass = tmp[1]; this.user = user; //System.out.println(user +","+ pass); if (!user.isEmpty() && !pass.isEmpty()) { // dieu kien login String sql = "SELECT * FROM Account where username='" + user + "' and passwork='" + pass + "'";//SQL - SELECT ACCOUNT mRs = mData.ExecuteSelectDB(sql); if (mRs.next()) { //Login thanh cong //lay thong tin tai khoan mListAccount.append(user + ",");
mFullName = mRs.getString("fullname"); return true; //login thanh cong } else { return false; } } else { return false; // login that bai } } catch (SQLException ex) { return false; } }
private String[] ReadClient() { String[] temp = null; try { String in = din.readUTF(); //System.out.print(in); if (!in.isEmpty()) { temp = in.split(","); } } catch (Exception e) { System.err.println("ERROR : ReadClient"); Server.CloseConnect(key); Server.SendtoClient("He thong:," + user + " da thoat khoi Room", false);
} return temp; } } ConnectData.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7Server;
private Connection conn = null; private Statement stt = null; private ResultSet rs = null;
public boolean ConnectDB() { try { // Load the JDBC driver String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
this.conn = DriverManager.getConnection(url); return true; } catch (Exception e) { // Could not find the database driver //System.out.println("Khong the tao Ket noi den Server DataBase"); return false; } }
protected boolean ExecuteDB(String str) { //false neu ko rescord if (this.conn != null) { try { Statement stt = this.conn.createStatement(); return stt.execute(str);
} catch (SQLException ex) { Logger.getLogger(ConnectData.class.getName()).log(Level.SEVERE, null, ex); return false; } finally { try { stt.close(); } catch (SQLException ex) { Logger.getLogger(ConnectData.class.getName()).log(Level.SEVERE, null, ex); } } } else { return false; } }
protected ResultSet ExecuteSelectDB(String str) { if (this.conn != null) { try { //System.out.print(str); Statement stt = this.conn.createStatement(); ResultSet rs = stt.executeQuery(str); return rs; // no record -> } catch (SQLException ex) { Logger.getLogger(ConnectData.class.getName()).log(Level.SEVERE, null, ex);
} } Client MLogin.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7Client;
import java.awt.event.KeyEvent;
Client mClient;
/** * 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() {
jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel();
jTextField1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextField1KeyPressed(evt); } });
jLabel1.setText("User");
jTextField2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTextField2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextField2KeyPressed(evt); } });
jButton1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton1.setText("Exit"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } });
jButton2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton2.setText("Login"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt);
} });
jButton3.setText("Create");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton3) .addGap(0, 210, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout. Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement .RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout. Alignment.LEADING, false) .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE) .addComponent(jTextField1))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Al ignment.TRAILING, false) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacem ent.UNRELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(86, 86, 86)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNREL ATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELAT ED) .addComponent(jLabel3) .addGap(8, 8, 8)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.BASELINE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(12, 12, 12) .addComponent(jButton3)) );
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: mClient = new Client(); if (mClient.ConnectServer("localhost", 7000)) { String user = jTextField1.getText(); String pass = jTextField2.getText(); if (!user.isEmpty() && !pass.isEmpty()) { if (mClient.Login(user, pass)) { MClient mMClient = new MClient(); mMClient.setmClient(mClient); mMClient.RunMsgMain(mClient.getDin()); mMClient.setVisible(true);
this.setVisible(false); } else { //Sai ten dang nhap hoac pass jLabel3.setText("Sai ten dang nhap hoac mat khau"); } } else { //Nhap day du user and pass jLabel3.setText("Nhap day du User and Pass"); } } else { //Server khong hoat dong jLabel3.setText("Sory! Server tam ngung hoat dong"); }
private void formKeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if(evt.getKeyCode()==KeyEvent.VK_ENTER){ jButton2ActionPerformed(null); } }
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
System.exit(0); }
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if(evt.getKeyCode()==KeyEvent.VK_ENTER){ jButton2ActionPerformed(null); } }
private void jTextField2KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if(evt.getKeyCode()==KeyEvent.VK_ENTER){ jButton2ActionPerformed(null); } }
/** * @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(MLogin.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MLogin.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MLogin.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MLogin.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex);
} //</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
} }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2;
// End of variables declaration } MClient.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7Client;
jList1.setListData(str); }
public void RunMsgMain(DataInputStream din) { InClient mIn = new InClient(din); Thread th1 = new Thread(mIn); th1.start(); }
/** * 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. */
jScrollPane1 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(jList1);
jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton1.setText("Send"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt); } });
jTextArea2.setColumns(20); jTextArea2.setRows(1); jTextArea2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextArea2KeyPressed(evt); } }); jScrollPane4.setViewportView(jTextArea2);
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RE LATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement .RELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane3))) .addGroup(layout.createSequentialGroup() .addGap(122, 122, 122)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELAT ED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RE LATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.LEADING)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: try { String str = jTextArea2.getText().trim(); if (!str.equals("")) { String str2 = mClient.getUser() + "," + str; mClient.getDos().writeUTF(str2); jTextArea2.setText(""); } } catch (Exception e) { //err } }
private void jTextArea2KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if(evt.getKeyCode()==KeyEvent.VK_ENTER){
jButton1ActionPerformed(null); } }
/** * @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(MClient.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MClient.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MClient.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MClient.class.getName()).log(java.util.loggin g.Level.SEVERE, null, ex); } //</editor-fold>
public void run() { new MClient().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JList jList1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextArea jTextArea2; // End of variables declaration
try { while (true) { String in = din.readUTF(); if (!in.isEmpty()) { temp = in.split(","); // xu ly khi nhan duoc du lieu if ("0".equals(temp[0])) { //setList Account String[] tmp = new String[temp.length - 1]; for (int i = 1; i < temp.length; i++) { tmp[i - 1] = temp[i]; } //set List account cho Client; jList1.setListData(tmp); } else { // Set Msgbox jTextArea1.append(temp[1] + ":" + temp[2] + "\n"); } } } } catch (Exception e) { System.err.println("ERROR : ReadClient"); } } }
} Client.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7Client;
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger;
//user private String user; private String pass; private String fullname;
public Client() { }
public boolean ConnectServer(String ip, int port) { try { mSocket = new Socket("localhost", 7000); dos = new DataOutputStream(mSocket.getOutputStream());
public boolean Login(String user, String pass) { try { this.user=user; if (!user.isEmpty() && !pass.isEmpty()) { if (mSocket != null) { dos.writeUTF(user + "," + pass); //Send User And Passwork String in = din.readUTF(); if (!in.isEmpty()) { String[] temp ; temp = in.split(","); if (Boolean.parseBoolean(temp[0])) { //login true fullname = temp[1]; return true; } } } } } catch (IOException ex) { // Read respone cua server
SQLServer 2008. DataBaseName : MsgData User :sa Pass: 123 Table: Account
jdbc:sqlserver://localhost:1433;Database=MsgData;User=sa;Password=123;
Cu 1: Server UDPTimeServer.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpserver;
class UDPTimeServer { public static void main(String args[]) throws Exception { //Gan cong 9876 cho chuong trinh DatagramSocket serverSocket = new DatagramSocket(9876); //Tao cac mang byte de chua dl gui va nhan System.out.println("Server is started"); byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024]; while(true) { //Tao goi rong de nhan du lieu tu client DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
//Nhan dl tu client serverSocket.receive(receivePacket); //Lay dia chi IP cua may client InetAddress IPAddress = receivePacket.getAddress(); //Lay port cua chuong trinh client int port = receivePacket.getPort(); //Lay ngay gio de gui nguoc lai client String request = new String(receivePacket.getData()); System.out.println(request); if(request.trim().equals("getDate")) sendData = new Date().toString().getBytes(); else sendData = "Server not know what you want?".getBytes();
} } }
Client UDPTimeClient.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpclient;
/** * * @author congthanh */ import java.net.*; class UDPTimeClient { public static void main(String args[]) throws Exception { DatagramSocket clientSocket = new DatagramSocket();//gan cong dong
InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; sendData = "getDate".getBytes();
//tao datagram co noi dung yeu cau loai dl de gui cho server DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.receive(receivePacket);//nhan dl tu server
Demo
Cu 2 : Server -UDPTimeServer2.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpserver; /** * * @author congthanh */ import java.io.*; import java.net.*; import java.util.*;
class UDPTimeServer2 {
public static void main(String args[]) throws Exception { //Gan cong 9876 cho chuong trinh DatagramSocket serverSocket = new DatagramSocket(9876); //Tao cac mang byte de chua dl gui va nhan System.out.println("Server is started");
while (true) {
byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; //Tao goi rong de nhan du lieu tu client DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
//Nhan dl tu client serverSocket.receive(receivePacket); //Lay dia chi IP cua may client InetAddress IPAddress = receivePacket.getAddress(); //Lay port cua chuong trinh client int port = receivePacket.getPort(); //Lay ngay gio de gui nguoc lai client String request = new String(receivePacket.getData()); System.out.println(request); if (request.trim().equals("getDate")) { sendData = new Date().toString().getBytes(); } else { sendData = "Server not know what you want?".getBytes(); }
serverSocket.send(sendPacket); } } } Client -UDPTimeClient2.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpclient;
class UDPTimeClient2 {
public static void main(String args[]) throws Exception { DatagramSocket clientSocket = new DatagramSocket();//gan cong dong
while (true) { byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; sendData = "getDate".getBytes(); //tao datagram co noi dung yeu cau loai dl de gui cho server DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); Thread.sleep(1000); clientSocket.send(sendPacket);//gui dl cho server
clientSocket.receive(receivePacket);//nhan dl tu server
Cu 3: Server UDPTimerServer3.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpserver;
/** * Nen tao moi lai mang byte de tranh truong hop SAI du lieu * @author congthanh */ import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import javax.sound.midi.SysexMessage; import sun.misc.Cleaner;
class UDPTimeServer3 {
public static void main(String args[]) throws Exception { //Gan cong 9876 cho chuong trinh DatagramSocket serverSocket = new DatagramSocket(9876);
while (true) { byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); //Nhan dl tu client serverSocket.receive(receivePacket); //Lay dia chi IP cua may client InetAddress IPAddress = receivePacket.getAddress(); //Lay port cua chuong trinh client int port = receivePacket.getPort(); //Lay ngay gio de gui nguoc lai client String request = new String(receivePacket.getData()); System.out.println(request); Date mDate = new Date(); Calendar mCalendar = Calendar.getInstance(); mCalendar.setTime(mDate); int a = 0; if (request.trim().equals("Day")) {
a = mCalendar.get(Calendar.DATE); } else if (request.trim().equals("Month")) { a = mCalendar.get(Calendar.MONTH); } else if (request.trim().equals("Year")) { a = mCalendar.get(Calendar.YEAR); } else if (request.trim().equals("Hour")) { a = mCalendar.get(Calendar.HOUR); } else if (request.trim().equals("Minute")) { a = mCalendar.get(Calendar.MINUTE); } else if (request.trim().equals("Second")) { a = mCalendar.get(Calendar.SECOND); } else { a = -1; } if (a == -1) { sendData = "Server not know what you want?".getBytes(); } else { sendData = Integer.toString(a).getBytes(); } DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
} } Client UDPTimeClient3.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpclient;
class UDPTimeClient3 {
public static void main(String args[]) throws Exception { DatagramSocket clientSocket = new DatagramSocket();//gan cong dong
//tao datagram co noi dung yeu cau loai dl de gui cho server DatagramPacket sendPacket; Scanner mScanner = new Scanner(System.in); //tao datagram rong de nhan dl
while (true) { byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); sendData = "getDate".getBytes(); System.out.print("Nhap vao yeu cau: "); sendData = (mScanner.nextLine().getBytes()); sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); //Thread.sleep(1000); clientSocket.send(sendPacket);//gui dl cho server clientSocket.receive(receivePacket);//nhan dl tu server
} }
Cu 4: Server
-
UDPTimeServer4.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpserver; /** * * @author congthanh */ import java.io.*; import java.net.*; import java.util.*;
class UDPTimeServer4 {
public static void main(String args[]) throws Exception { //Gan cong 9876 cho chuong trinh DatagramSocket serverSocket = new DatagramSocket(9876);
while (true) { byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; //Tao goi rong de nhan du lieu tu client DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
//Nhan dl tu client serverSocket.receive(receivePacket); //Lay dia chi IP cua may client InetAddress IPAddress = receivePacket.getAddress(); //Lay port cua chuong trinh client int port = receivePacket.getPort(); //Lay ngay gio de gui nguoc lai client String request = new String(receivePacket.getData()); System.out.println(request); if (request.trim().equals("getDate")) { sendData = new Date().toString().getBytes(); } else { sendData = "Server not know what you want?".getBytes(); }
UDPTimeClient4.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpclient;
/** * set : gan gia tri * get : lay gia tri * Tao doi tuong phai de ngoai vong lap * chuyen doi tu mang byte sang string used funtion str.trim()//lam sach vung byte null * chu y kieu tra ve trong mot ham * @author congthanh */ import java.io.*;
import java.net.*;
class UDPTimeClient4 {
public static void main(String args[]) throws Exception { DatagramSocket clientSocket = new DatagramSocket();//gan cong dong
while (true) { byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; sendData = "getDate".getBytes(); //tao datagram co noi dung yeu cau loai dl de gui cho server DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); Thread.sleep(1000); clientSocket.send(sendPacket);//gui dl cho server
clientSocket.receive(receivePacket);//nhan dl tu server
mFrame4.mSetTime(str.trim());
//System.out.println(str); } //clientSocket.close(); } }
Cu 5: Server Server.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai5Server;
import java.net.SocketException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger;
public Server() { try { mDatagramSocket = new DatagramSocket(9876); System.out.println("Server is started"); } catch (SocketException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } }
public void run() { try { while (true) { byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; //Tao goi rong de nhan du lieu tu client mInPacket = new DatagramPacket(receiveData, receiveData.length);
//Nhan dl tu client mDatagramSocket.receive(mInPacket); //Lay dia chi IP cua may client InetAddress IPAddress = mInPacket.getAddress(); //Lay port cua chuong trinh client int port = mInPacket.getPort(); //Lay ngay gio de gui nguoc lai client String request = new String(mInPacket.getData()); System.out.println(request);
//Gui dl lai cho client mDatagramSocket.send(mOutPacket); } } catch (Exception e) { } } public String mTimeZone(String country) { // // // // } String[] timeZoneIDList=TimeZone.getAvailableIDs(); for(String timeZoneID:timeZoneIDList){ System.out.print(timeZoneID);
// Calendar mCalendar=Calendar.getInstance(TimeZone.getTimeZone("Pacific/Fiji")); // String mTime=mCalendar.get(Calendar.HOUR)+ ":" + mCalendar.get(Calendar.MINUTE) + ":" + mCalendar.get(Calendar.SECOND); Date date = new Date(); //System.out.println(country); DateFormat firstFormat = new SimpleDateFormat("HH:mm:ss"); TimeZone firstTime = TimeZone.getTimeZone(country.toString()); firstFormat.setTimeZone(firstTime);
String str=firstFormat.format(date); return str; } public static void main(String[] args) { Server mServer = new Server();
mServer.run();
} } Client Client.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai5Client;
/** * * @author congthanh */ public class Client { private DatagramSocket mDatagramSocket; private DatagramPacket mOutPacket,mInPacket; public static String country; JFrame mFrame;
static{ country = "America/Phoenix"; } public Client() { try { mDatagramSocket = new DatagramSocket(); mFrame = new JFrame(); mFrame.setVisible(true); } catch (SocketException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); }
public void run(){ try { InetAddress IPAddress = InetAddress.getByName("localhost"); while (true) { byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024];
//System.out.println(country);
sendData = country.getBytes(); //tao datagram co noi dung yeu cau loai dl de gui cho server mOutPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); Thread.sleep(1000); mDatagramSocket.send(mOutPacket);//gui dl cho server
mDatagramSocket.receive(mInPacket);//nhan dl tu server
String str = new String(mInPacket.getData());//lay dl tu packet nhan duoc mFrame.setjTextField1(str.trim()); // System.out.println(str); }} catch(Exception ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }
public static void main(String[] args) { Client mClient = new Client(); mClient.run();
} JFrame.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai5Client;
import java.util.TimeZone;
/** * Creates new form JFrame */ public JFrame() { initComponents(); // // String[] timeZoneIDList = TimeZone.getAvailableIDs(); for (String timeZoneID : timeZoneIDList) {
// // // // } }
jComboBox1.addItem(timeZoneID);
jComboBox1.setSelectedItem(Client.country);
/** * 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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "New York", "Hanoi", "Tokyo", "Paris", "Jakarta", "Seoul" })); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } });
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(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jTextField1)) .addContainerGap(57, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(46, 46, 46) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.BASELINE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(57, Short.MAX_VALUE))
);
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling co String str = (String) jComboBox1.getSelectedItem(); if ("New York".equals(str)) { Client.country = "America/Phoenix"; } else if ("Hanoi".equals(str)) { Client.country = "Asia/Ho_Chi_Minh"; } else if ("Tokyo".equals(str)) { Client.country = "Asia/Tokyo"; } else if ("Paris".equals(str)) { Client.country = "Europe/Paris"; } else if ("Jakarta".equals(str)) { Client.country = "Asia/Jakarta"; } else { Client.country = "Asia/Seoul"; } }
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
/** * @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(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } //</editor-fold>
public void run() { new JFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JComboBox jComboBox1;
Cu 6: Server Server.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai6Server;
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.text.DecimalFormat; import java.util.logging.Level; import java.util.logging.Logger;
/** *
public Server() { try { mDatagramSocket = new DatagramSocket(9876); System.out.println("Server is started"); } catch (SocketException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } }
public void run() { try { while (true) { byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; mInPacket = new DatagramPacket(receiveData, receiveData.length); mDatagramSocket.receive(mInPacket); InetAddress IPAdaress = mInPacket.getAddress(); int port = mInPacket.getPort();
} } catch (Exception e) { } }
String[] tmp; tmp = str.split(","); char[] a = tmp[2].trim().toCharArray(); double ketqua = 0; double so1 = Double.parseDouble(tmp[0]); double so2 = Double.parseDouble(tmp[1]);
switch (a[0]) { case '+': ketqua = so1 + so2; break; case '-': ketqua = so1 - so2; break; case '*': ketqua = so1 * so2; break; case '/': ketqua = so1 / so2; break; default: break; }
public static void main(String[] args) { Server mServer = new Server(); mServer.run(); } } Client Client.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai6Client;
private DatagramSocket mDatagramSocket; private DatagramPacket mInPacket, mOutPacket; private JFrame mFrame;
public Client() { try { mDatagramSocket = new DatagramSocket(); // // mFrame = new JFrame(); mFrame.setVisible(true); } catch (SocketException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }
public String Send(String str) { try { InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; sendData = str.getBytes(); mOutPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); mDatagramSocket.send(mOutPacket); System.out.print(str);
//System.out.println(new String(mInPacket.getData()).trim()); return new String(mInPacket.getData()).trim(); } catch (Exception ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); return "0"; } } } JFrame.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai6Client;
/**
initComponents(); }
/** * 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(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox(); jTextField3 = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jTextField1.setText(" "); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } });
jTextField3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jTextField3.setText(" "); jTextField3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField3ActionPerformed(evt); } });
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setText("Ket Qua"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } });
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(47, 47, 47) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELAT ED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING, false) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE) .addComponent(jTextField2) .addComponent(jTextField3)) .addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(107, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(89, 89, 89)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel5) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING, false) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNREL ATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(3, 3, 3) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addContainerGap(54, Short.MAX_VALUE)) );
private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String a, b, c, noi; a = jTextField1.getText(); b = jTextField2.getText(); c = (String) jComboBox1.getSelectedItem(); noi = a + "," + b + "," + c; Client mClient = new Client(); jTextField3.setText(mClient.Send(noi));
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }
/**
* @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(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } //</editor-fold>
public void run() { new JFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JComboBox jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5;
private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; // End of variables declaration }
Cu 7: Server Server.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7;
/** * * @author congthanh */ import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Enumeration; import java.util.Hashtable;
class Server {
private DatagramSocket mSocket; private DatagramPacket mInPacket, mOutPacket; private Hashtable mHashtable; private ClientAddress mClientAddress; private int i = 0;
public Server() { try { mSocket = new DatagramSocket(9876); System.out.println("Server is started"); mHashtable = new Hashtable(); } catch (Exception e) { } }
public static void main(String[] args) { Server mServer = new Server(); mServer.Receive(); }
while (true) {
byte[] receiveData = new byte[1024]; mInPacket = new DatagramPacket(receiveData, receiveData.length); mSocket.receive(mInPacket); //Lay dia chi IP cua may client InetAddress IPAddress = mInPacket.getAddress(); //Lay port cua chuong trinh client int port = mInPacket.getPort(); //Lay ngay gio de gui nguoc lai client String request = new String(mInPacket.getData()).trim(); //System.out.println(request); //Xu ly AddClient(IPAddress, port); Send(request); // System.out.println("Send "); } } catch (Exception e) { } }
int port; Enumeration names = mHashtable.keys(); while (names.hasMoreElements()) { String str = (String) names.nextElement(); ClientAddress mt = (ClientAddress) mHashtable.get(str); byte[] sendData = new byte[1024]; sendData = msend.getBytes(); mOutPacket = new DatagramPacket(sendData, sendData.length, mt.IP, mt.Port);
public void AddClient(InetAddress IP, int Port) { //System.out.println("Dia chi" + IP + " _ " + Port); ClientAddress mAddress = new ClientAddress(IP, Port); Enumeration names = mHashtable.keys(); boolean check = false;
ClientAddress mt = (ClientAddress) mHashtable.get(str); if (mt.compare(mAddress)) { check = true; } } if (!check) //neu dia chi Client chua co trong danh sach --- thi add dia chi vao HasTable { mHashtable.put("Client" + ++i, mAddress); } } } ClientAddress.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7;
import java.net.InetAddress;
public ClientAddress() { }
public boolean compare(ClientAddress mClient) { String ip1=mClient.IP.toString(); String ip2=this.IP.toString(); // System.out.println(ip1 + " " + ip2 + " " + this.Port + " " + mClient.Port); if (ip1.equals(ip2) && this.Port == mClient.Port) { return true; } else { return false; } } } Client
Client.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7;
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.logging.Level; import java.util.logging.Logger;
private DatagramSocket mDatagramSocket; private DatagramPacket mInPacket, mOutPacket; // private JFrame mFrame;
public Client() {
try { mDatagramSocket = new DatagramSocket(); } catch (SocketException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }
InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; sendData = str.getBytes(); mOutPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); mDatagramSocket.send(mOutPacket);
byte[] receiveData = new byte[1024]; mInPacket = new DatagramPacket(receiveData, receiveData.length); mDatagramSocket.receive(mInPacket); String a=new String(mInPacket.getData()).trim(); System.out.println(a); ClientJFrame.jTextArea1.append(a+"\n");
@Override public void run() { Receive(); } } ClientJFrame.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7;
import java.awt.event.KeyEvent;
public void setUser(String user) { this.user = user; mClient.Send("He thong:: " + this.user + " da tham gia Room"); }
/** * Creates new form ClientJFrame */ public ClientJFrame() { initComponents(); mClient = new Client(); Thread th = new Thread(mClient); th.start(); }
/** * 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() {
jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea2.setColumns(20);
jTextArea2.setRows(5); jTextArea2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextArea2KeyPressed(evt); } }); jScrollPane2.setViewportView(jTextArea2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alig nment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement .RELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup() .addGap(133, 133, 133) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNREL ATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNREL ATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING, false) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE)) .addContainerGap(19, Short.MAX_VALUE)) );
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String str = user + ": " + jTextArea2.getText().trim(); if (jTextArea2.getText().trim().length() > 0) { mClient.Send(str); } jTextArea2.setText(null);
private void jTextArea2KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if(evt.getKeyCode()==KeyEvent.VK_ENTER){ jButton1ActionPerformed(null); } }
/** * @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(ClientJFrame.class.getName()).log(java.util.lo gging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.lo gging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.lo gging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientJFrame.class.getName()).log(java.util.lo gging.Level.SEVERE, null, ex); } //</editor-fold>
} // Variables declaration - do not modify private javax.swing.JButton jButton1; public javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; public static javax.swing.JTextArea jTextArea1; private javax.swing.JTextArea jTextArea2; // End of variables declaration } JFrame.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7;
import java.awt.event.KeyEvent;
/** * 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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
});
jButton1.setText("Login"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jButton1KeyPressed(evt); } });
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(38, 38, 38) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(58, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(41, 41, 41) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignmen t.LEADING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE) .addComponent(jTextField1)) .addContainerGap(38, Short.MAX_VALUE)) );
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: if (!jTextField1.getText().isEmpty()) { ClientJFrame mFrame = new ClientJFrame(); mFrame.setUser(jTextField1.getText()); mFrame.jLabel1.setText(jTextField1.getText()); mFrame.setVisible(true);
this.setVisible(false);
} }
private void jButton1KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: }
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if(evt.getKeyCode()==KeyEvent.VK_ENTER){ jButton1ActionPerformed(null); } }
/** * @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(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging .Level.SEVERE, null, ex); } //</editor-fold>
/*
public void run() { new JFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JTextField jTextField1; // End of variables declaration }