Sie sind auf Seite 1von 178

THC HNH TCP

Cu 1:

TimeServer.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Server;

/** * * @author congthanh */ import java.io.DataOutputStream; import java.net.*; import java.util.Date;

public class TimeServer {

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;

/** * * @author congthanh */ import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket;

public class TimeClient {

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;

/** * * @author congthanh */ import java.net.ServerSocket; import java.net.Socket;

public class TimeServer {

public static int port = 7000;

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(); }

} }

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 class TimeClient extends Thread{

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) {

Logger.getLogger(TimeClient.class.getName()).log(Level.SEVERE, null, 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 DoConn(Socket msocket) { this.msocket=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

/** * * @author congthanh */ import java.net.ServerSocket; import java.net.Socket;

public class TimeServer {

public static int port = 7000;

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.BufferedReader; import java.io.DataOutputStream;

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;

/** * * @author congthanh */ public class DoConn implements Runnable {

private Socket msocket;

private BufferedReader din = null; private DataOutputStream dos = null; //DataInputStream din = null; public DoConn(Socket msocket) { this.msocket = msocket; }

// // //

public void setCountry(String country) { this.country = country; }

public void run() {

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) {

Logger.getLogger(DoConn.class.getName()).log(Level.SEVERE, null, ex); } } }

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; } }

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 class TimeClient extends Thread{ public static String country="Asia/Ho_Chi_Minh";

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);

din = new DataInputStream(socket.getInputStream()); String time = din.readUTF();

//System.out.print(time); jf1.mSetTime(time);

//Socket socket = new Socket("localhost", 7000);

// // //

DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF(ClientJFrame.country); System.out.println(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;

/** * * @author congthanh */ public class ClientJFrame extends javax.swing.JFrame {

/** * Creates new form ClientJFrame */

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() {

jComboBox1 = new javax.swing.JComboBox(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton();

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); } });

jButton1.setText("OK"); 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(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)) );

pack(); }// </editor-fold>

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>

/* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() {

public void run() { } }); }

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;

/** * * @author congthanh */ import java.net.ServerSocket; import java.net.Socket;

public class Bai5Server {

public static int port = 7000;

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(); Bai5Do mconn=new Bai5Do(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();

} }
o

Bai5Do.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Server;

import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level;

import java.util.logging.Logger;

/** * * @author congthanh */ public class Bai5Do implements Runnable {

private Socket mSocket; private String FileName = "File.txt"; private double so1, so2; private boolean replay = true; DataOutputStream dos = null; DataInputStream din = null;

public Bai5Do(Socket mSocket) { this.mSocket = mSocket; }

public void run() { try { String st = null; dos = new DataOutputStream(mSocket.getOutputStream()); din = new DataInputStream(mSocket.getInputStream());

while (replay) { try {

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) {

Logger.getLogger(Bai5Do.class.getName()).log(Level.SEVERE, null, 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;

//stringbuffer chua noi dung file StringBuffer strBuffers = new StringBuffer();

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

Bai5Client.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.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 class Bai5Client {

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");

replay = false; dos.flush(); break; }

} 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;

/** * * @author congthanh

*/ public class StartServer extends javax.swing.JFrame{

private static Socket mSocket;

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 ");

} }

} 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 Bai6Server;

import java.net.ServerSocket; import java.net.Socket; import java.util.Enumeration; import java.util.Hashtable;

/** * * @author congthanh

*/ public class Server { // properties Server

private ServerSocket mServerSocket; protected static Hashtable mHashtable;

//set and get properties public Server() { mHashtable = new Hashtable(); }

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; }

} catch (Exception e) { System.err.println("Port da duoc chiem dung"); 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 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;

/** * * @author congthanh */ public class DoServer implements Runnable {

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 {

mListAccount = new StringBuffer(); }

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());

} catch (Exception e) { System.err.println(e); } }

@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();

} else { //login that bai} SendtoClient("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() {

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; // login that bai }

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:
-

MLogin.java /* * To change this template, choose Tools | Templates

* and open the template in the editor. */ package Bai6Client;

import java.awt.event.KeyEvent;

/** * * @author congthanh */ public class MLogin extends javax.swing.JFrame {

Client mClient;

/** * Creates new form MLogin */ public MLogin() { 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() {

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();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { formKeyPressed(evt); } });

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.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel1.setText("User");

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");

jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("Login");

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)) );

pack(); }// </editor-fold>

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 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); } }

/** * @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>

/* * Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() { new MLogin().setVisible(true);

} }); } // 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;

import java.awt.event.KeyEvent; import java.io.DataInputStream;

/** * * @author congthanh */ public class MClient extends javax.swing.JFrame {

private Client mClient;

public void setmClient(Client mClient) { this.mClient = mClient; }

public void SetListAccount(String[] str) { jList1.setListData(str); }

public void SetMsg(String str) { jTextArea1.append(str); }

public void RunMsgMain(DataInputStream din) { InClient mIn = new InClient(din); Thread th1 = new Thread(mIn); th1.start(); }

/** * Creates new form MClient */ public MClient() { 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() {

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);

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("List User");

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); }

});

jTextArea1.setColumns(20); jTextArea1.setEditable(false); jTextArea1.setRows(5); jScrollPane3.setViewportView(jTextArea1);

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);

jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("ROOM CHAT");

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) .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)

.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane4))))) );

pack(); }// </editor-fold>

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>

/* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() {

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

class InClient implements Runnable {

private DataInputStream din;

public InClient(DataInputStream din) { this.din = din; }

@Override public void run() { Read(); }

public void Read() { String[] temp = null;

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;

/** * * @author congthanh */ public class Client { //properties

private Socket mSocket; private DataInputStream din; private DataOutputStream dos;

//user private String user; private String pass; private String fullname;

public Client() { }

public DataInputStream getDin() { return din; }

public DataOutputStream getDos() { return dos; }

public String getUser() { return user; }

public boolean ConnectServer(String ip, int port) { try { mSocket = new Socket("localhost", 7000); dos = new DataOutputStream(mSocket.getOutputStream());

din = new DataInputStream(mSocket.getInputStream()); return true; } catch (Exception e) { return false; } }

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

Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } return false; } }

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;

/** * * @author congthanh */ public class StartServer extends javax.swing.JFrame{

private static Socket mSocket;

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;

import java.net.ServerSocket; import java.net.Socket; import java.util.Enumeration; import java.util.Hashtable;

/** *

* @author congthanh */ public class Server { // properties Server

private ServerSocket mServerSocket; protected static Hashtable mHashtable;

//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; }

} catch (Exception e) { System.err.println("Port da duoc chiem dung"); 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;

/** * * @author congthanh */ public class DoServer implements Runnable {

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());

} catch (Exception e) { System.err.println(e); } }

@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();

} else { //login that bai} SendtoClient("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;

import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger;

/** * * @author congthanh */ public class ConnectData {

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";

Class.forName(driverName); // Create a connection to the database String url = "jdbc:sqlserver://localhost:1433;Database=MsgData;User=sa;Password=123;";

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);

return rs=null; } } else { return rs=null; } // // } ResultSet rs=null; return rs;

protected void CloseConnectDB(Connection conn) throws SQLException { if (conn != null) { conn.close(); }

} } Client MLogin.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Bai7Client;

import java.awt.event.KeyEvent;

/** * * @author congthanh */ public class MLogin extends javax.swing.JFrame {

Client mClient;

/** * Creates new form MLogin */ public MLogin() { 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() {

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();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { formKeyPressed(evt); } });

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.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

jLabel1.setText("User");

jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel2.setText("Pass");

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");

jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("Login");

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)) );

pack(); }// </editor-fold>

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>

/* * Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() { new MLogin().setVisible(true);

} }); } // 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;

import java.awt.event.KeyEvent; import java.io.DataInputStream;

/** * * @author congthanh */ public class MClient extends javax.swing.JFrame {

private Client mClient;

public void setmClient(Client mClient) { this.mClient = mClient; }

public void SetListAccount(String[] str) {

jList1.setListData(str); }

public void SetMsg(String str) { jTextArea1.append(str); }

public void RunMsgMain(DataInputStream din) { InClient mIn = new InClient(din); Thread th1 = new Thread(mIn); th1.start(); }

/** * Creates new form MClient */ public MClient() { 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() {

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);

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("List User");

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); } });

jTextArea1.setColumns(20); jTextArea1.setEditable(false); jTextArea1.setRows(5); jScrollPane3.setViewportView(jTextArea1);

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);

jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("ROOM CHAT");

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) .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)

.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane4))))) );

pack(); }// </editor-fold>

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>

/* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() {

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

class InClient implements Runnable {

private DataInputStream din;

public InClient(DataInputStream din) { this.din = din; }

@Override public void run() { Read(); }

public void Read() { String[] temp = null;

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;

/** * * @author congthanh */ public class Client { //properties

private Socket mSocket; private DataInputStream din; private DataOutputStream dos;

//user private String user; private String pass; private String fullname;

public Client() { }

public DataInputStream getDin() { return din; }

public DataOutputStream getDos() { return dos; }

public String getUser() { return user; }

public boolean ConnectServer(String ip, int port) { try { mSocket = new Socket("localhost", 7000); dos = new DataOutputStream(mSocket.getOutputStream());

din = new DataInputStream(mSocket.getInputStream()); return true; } catch (Exception e) { return false; } }

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

Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } return false; } } CSDL: -

SQLServer 2008. DataBaseName : MsgData User :sa Pass: 123 Table: Account

jdbc:sqlserver://localhost:1433;Database=MsgData;User=sa;Password=123;

THC HNH UDP

Cu 1: Server UDPTimeServer.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpserver;

/** * * @author congthanh */ import java.net.*; import java.util.*;

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();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);

//Gui dl lai cho client serverSocket.send(sendPacket);

} } }

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.send(sendPacket);//gui dl cho server

//tao datagram rong de nhan dl DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);//nhan dl tu server

String str= new String(receivePacket.getData());//lay dl tu packet nhan duoc System.out.println(str); clientSocket.close(); } }

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(); }

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);

//Gui dl lai cho client

serverSocket.send(sendPacket); } } } Client -UDPTimeClient2.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpclient;

/** * * @author congthanh */ import java.io.*; import java.net.*;

class UDPTimeClient2 {

public static void main(String args[]) throws Exception { DatagramSocket clientSocket = new DatagramSocket();//gan cong dong

InetAddress IPAddress = InetAddress.getByName("localhost");

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

//tao datagram rong de nhan dl DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);//nhan dl tu server

String str = new String(receivePacket.getData());//lay dl tu packet nhan duoc System.out.println(str); } //clientSocket.close(); } }

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);

//Tao cac mang byte de chua dl gui va nhan System.out.println("Server is started");

//Tao goi rong de nhan du lieu tu client

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);

//Gui dl lai cho client serverSocket.send(sendPacket); }

} } Client UDPTimeClient3.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package udpclient;

/** * * @author congthanh */ import java.io.*; import java.net.*; import java.util.Scanner;

class UDPTimeClient3 {

public static void main(String args[]) throws Exception { DatagramSocket clientSocket = new DatagramSocket();//gan cong dong

InetAddress IPAddress = InetAddress.getByName("localhost");

//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

String str = new String(receivePacket.getData());//lay dl tu packet nhan duoc System.out.println(str); } //clientSocket.close();

} }

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);

//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(); }

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);

//Gui dl lai cho client serverSocket.send(sendPacket); } } } Client


-

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

InetAddress IPAddress = InetAddress.getByName("localhost"); JFrame4 mFrame4 = new JFrame4(); mFrame4.setVisible(true);

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

//tao datagram rong de nhan dl DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);//nhan dl tu server

String str = new String(receivePacket.getData());//lay dl tu packet nhan duoc

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.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress;

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;

/** * * @author congthanh */ public class Server {

DatagramPacket mOutPacket, mInPacket; DatagramSocket mDatagramSocket;

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);

String time=mTimeZone(request); sendData=time.getBytes(); mOutPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);

//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;

import java.net.*; import java.util.logging.Level; import java.util.logging.Logger;

/** * * @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

//tao datagram rong de nhan dl mInPacket = new DatagramPacket(receiveData, receiveData.length);

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;

/** * * @author congthanh */ public class JFrame extends javax.swing.JFrame {

/** * Creates new form JFrame */ public JFrame() { initComponents(); // // String[] timeZoneIDList = TimeZone.getAvailableIDs(); for (String timeZoneID : timeZoneIDList) {

// // // // } }

jComboBox1.addItem(timeZoneID);

jComboBox1.setSelectedItem(Client.country);

public void setjTextField1(String str) { this.jTextField1.setText(str); }

/** * 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() {

jComboBox1 = new javax.swing.JComboBox(); jButton1 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField();

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); } });

jButton1.setText("OK"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } });

jTextField1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jTextField1.setText(" ");

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))

);

pack(); }// </editor-fold>

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>

/* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() {

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.JTextField jTextField1; // End of variables declaration }

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;

/** *

* @author congthanhD */ public class Server {

DatagramSocket mDatagramSocket; DatagramPacket mOutPacket, mInPacket;

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();

String request = new String(mInPacket.getData()); System.out.println(request);

//tinh toan du lieu sendData = Double.toString(math(request)).getBytes();

// gui du lieu mOutPacket = new DatagramPacket(sendData, sendData.length, IPAdaress, port); mDatagramSocket.send(mOutPacket);

} } catch (Exception e) { } }

public double math(String str) { try {

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; }

DecimalFormat df = new DecimalFormat("##.#");

return Double.parseDouble(df.format(ketqua)); } catch (Exception e) { return 0.0; }

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;

import java.net.*; import java.util.logging.Level; import java.util.logging.Logger; import sun.nio.cs.ext.MSISO2022JP;

/** * * @author congthanh */ public class Client {

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);

mInPacket = new DatagramPacket(receiveData, receiveData.length); mDatagramSocket.receive(mInPacket);

//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;

/** * * @author congthanh */ public class JFrame extends javax.swing.JFrame {

/**

* Creates new form JFrame */ public JFrame() {

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);

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("Nhap a");

jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("Nhap b");

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); } });

jTextField2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jTextField2.setText(" ");

jLabel3.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N jLabel3.setText("Chon phep toan");

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); } });

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); } });

jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setText("Mini Calculator");

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)) );

pack(); }// </editor-fold>

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>

/* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() {

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(); }

public void Receive() { try {

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) { } }

public void Send(String msend) { try { InetAddress IP;

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);

//System.out.println("Send"); //Gui dl lai cho client mSocket.send(mOutPacket); } } catch (Exception e) { } }

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;

while (names.hasMoreElements()) { String str = (String) names.nextElement();

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;

/** * * @author congthanh */

public class ClientAddress {

public InetAddress IP; public int Port;

public ClientAddress() { }

public ClientAddress(InetAddress IP, int Port) { this.IP = IP; this.Port = Port; }

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;

/** * * @author congthanh */ public class Client implements Runnable {

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); } }

public void Send(String str) { try {

InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; sendData = str.getBytes(); mOutPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); mDatagramSocket.send(mOutPacket);

} catch (Exception ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }

public void Receive() { try { while (true) {

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");

} } catch (Exception ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }

@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;

/** * * @author congthanh */ public class ClientJFrame extends javax.swing.JFrame {

private String user; private Client mClient;

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);

jTextArea1.setColumns(20); jTextArea1.setEditable(false); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1);

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);

jButton1.setText("jButton1"); 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() .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)) );

pack(); }// </editor-fold>

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>

/* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() {

public void run() { new ClientJFrame().setVisible(true); } });

} // 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;

/** * * @author congthanh */ public class JFrame extends javax.swing.JFrame {

/** * Creates new form JFrame */ public JFrame() { 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() {

jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextField1KeyPressed(evt); }

});

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)) );

pack(); }// </editor-fold>

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>

/*

* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() {

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 }

Das könnte Ihnen auch gefallen