Anda di halaman 1dari 31

Tm c chung TCP Client package Bai1; import java.io.*; import java.net.

Socket; public class Bai1_Client { public static void main(String argv[]) throws Exception { try { BufferedReader banphim = new BufferedReader(new InputStreamReader(System.in)); Socket s = new Socket("localhost",9999); DataOutputStream outToServer = new DataOutputStream(s.getOutputStream()); System.out.print("Nhap n: "); int so = Integer.parseInt(banphim.readLine()); outToServer.writeInt(so); DataInputStream inFromClient = new DataInputStream(s.getInputStream()); String Uoc = inFromClient.readLine(); System.out.println(Uoc); } catch (Exception e) { System.out.println("Loi" + e); } } } Server package Bai1; import java.io.*; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Bai1_Server {

public static void main(String argv[]) throws IOException { ServerSocket ss = new ServerSocket(9999) ; System.out.println("Hello, wellcome to Server. Waiting.... "); while(true) { Socket connectToClient = ss.accept(); PrintWriter out = null; out = new PrintWriter(connectToClient.getOutputStream(), true); DataInputStream inFromClient = new DataInputStream(connectToClient.getInputStream()); int n = inFromClient.readInt(); int[] Uoc = new int[n]; int spt = TimUoc(n, Uoc); String kq = ""; for(int i = 0; i < spt; i++) { kq += Uoc[i] + " "; } out.println(kq); System.out.println("Done!!!"); } } public static int TimUoc(int n, int[] Uoc) { int j = 0; for(int i = 1;i < n; i++) { if(n%i == 0) { Uoc[j] = i; j++; } } return j; }

} UDP Client package Bai1.UDP; import java.io.BufferedReader; import java.io.IOException; import java.net.*; import java.util.logging.Level; import java.util.logging.Logger; public class Client extends javax.swing.JFrame { public Client() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { label1 = new java.awt.Label(); textField1 = new java.awt.TextField(); button1 = new java.awt.Button(); label2 = new java.awt.Label(); textArea1 = new java.awt.TextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); label1.setText("n ="); textField1.setName("txtNhap"); button1.setLabel("Tm c"); button1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { button1ActionPerformed(evt); } });

label2.setText("c"); textArea1.setName("txtKq"); 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(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textArea1, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addComponent(textArea1, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_button1ActionPerformed try { // TODO add your handling code here: String str = textField1.getText(); DatagramSocket clientSk = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] reData = new byte[1024]; byte[] seData = new byte[1024]; seData = str.getBytes(); DatagramPacket sePacket = new DatagramPacket(seData, seData.length, IPAddress, 9999); clientSk.send(sePacket); DatagramPacket rePacket = new DatagramPacket(reData, reData.length); clientSk.receive(rePacket); String modiStr = new String(rePacket.getData()).trim(); textArea1.setText(modiStr); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_button1ActionPerformed public static void main(String args[]) {

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(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Client().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private java.awt.Button button1; private java.awt.Label label1; private java.awt.Label label2; private java.awt.TextArea textArea1; private java.awt.TextField textField1; } Server

package Bai1.UDP; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import javax.swing.JOptionPane; public class server extends javax.swing.JFrame { public server() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { label1 = new java.awt.Label(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); label1.setText("Server is waiting..."); 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(61, 61, 61) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(47, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18)

.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(44, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void formWindowOpened(java.awt.event.WindowEvent evt) {//GENFIRST:event_formWindowOpened // TODO add your handling code here: try { DatagramSocket serverSk = new DatagramSocket(9999); byte[] reData = new byte[1024]; byte[] seData = new byte[1024]; while(true) { DatagramPacket rePacket = new DatagramPacket(reData, reData.length); serverSk.receive(rePacket); String sentence = new String(rePacket.getData()).trim(); int n = Integer.parseInt(sentence); InetAddress IPAddress = rePacket.getAddress(); int port = rePacket.getPort(); int[] Uoc = new int[n]; int spt = TimUoc(n, Uoc); String kq = ""; for(int i = 0; i < spt; i++) { kq += Uoc[i] + " "; } seData = kq.getBytes(); DatagramPacket sePacket = new DatagramPacket(seData, seData.length, IPAddress, port); serverSk.send(sePacket); JOptionPane.showMessageDialog(this, "Done!!!");

} } catch (Exception e) {} }//GEN-LAST:event_formWindowOpened public static int TimUoc(int n, int[] Uoc) { int j = 0; for(int i = 1;i < n; i++) { if(n%i == 0) { Uoc[j] = i; j++; } } return j; } /** * @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(server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(server.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 server().setVisible(true); } }); } private java.awt.Label label1; } MultiThread Client package MultiThread;

import java.io.*; import java.net.Socket; import java.net.UnknownHostException; public class Client { public static void main(String []args) throws IOException { Socket clientSocket = new Socket("localhost", 8888); System.out.println("kt ni thnh cng"); //to lung d liu nhp t bn phm DataInputStream inFromUser = new DataInputStream(System.in); //to lung d liu nhn t server DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream()); //to lung d liu gi ln server DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); while(true) { try { System.out.println("\nClient: "); //nhp d liu t bn phm gi ln server String ask = inFromUser.readLine(); outToServer.writeBytes(ask + "\n"); //c d liu t server ri in ra mn hnh String listen = inFromServer.readLine(); System.out.println("\nServer: " + listen); } catch (UnknownHostException e ) { System.err.println("khng tm thy my ch"); System.exit(1); } catch(IOException e) { System.err.println("Khng th kt ni vi my ch");

System.exit(1); } } } } Server package MultiThread; import java.net.Socket; import java.io.*; import java.net.ServerSocket; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8888); System.out.print("khi to my ch thnh cng"); while(true) { //to 1 thread mi khi c 1 kt ni thnh cng new ThreadSocket(serverSocket.accept()).start(); System.out.println("c 1 kt ni n"); } } catch(IOException ex) { System.out.println("Exception: " +ex.getMessage()); } } } ThreadSocket package MultiThread; import java.io.*; import java.net.Socket; public class ThreadSocket extends Thread

{ Socket socket; public ThreadSocket(Socket psocket) { this.socket = psocket; } @ Override public void run() { try { //to lung d liu nhp t bn phm DataInputStream inFromServer = new DataInputStream(System.in); //to lung d liu nhn t client DataInputStream inFromClient = new DataInputStream(socket.getInputStream()); //to lung gi d liu v client DataOutputStream outToClient =new DataOutputStream(socket.getOutputStream()); while(true) { //c d liu t client gi ti ri in ra String listen = inFromClient.readLine(); System.out.println("\nClient: " + listen); System.out.println("\nServer: "); //nhp d liu ri gi v client String ask = inFromServer.readLine(); outToClient.writeBytes(ask + "\n"); } } catch(Exception e) { e.printStackTrace(); } } }

Gii phng trnh bc 2 Client package socket; import java.io.*; import java.net.Socket; public class GiaiPTB2_Client { public static void main(String argv[]) throws Exception { try { BufferedReader banPhim = new BufferedReader(new InputStreamReader(System.in)); Socket s = new Socket("localhost", 9999); DataOutputStream outToServer = new DataOutputStream(s.getOutputStream()); GiaiPTB2_Client_Thread t=new GiaiPTB2_Client_Thread(s); System.out.print("Nhap vao 3 so a b c \n"); System.out.print("Nhap so thu nhat: "); float so1 = Float.parseFloat(banPhim.readLine()); System.out.print("Nhap so thu hai: "); float so2 = Float.parseFloat(banPhim.readLine()); System.out.print("Nhap vao so thu ba :"); float so3 = Float.parseFloat(banPhim.readLine()); outToServer.writeFloat(so1); outToServer.writeFloat(so2); outToServer.writeFloat(so3); t.run(); } catch (IOException e) { System.out.println("Loi" + e); } } } ClientThread

package socket; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.*; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; public class GiaiPTB2_Client_Thread { private Socket ConnectToServer = new Socket(); // khoi tao mot socket de ket noi toi client public GiaiPTB2_Client_Thread(Socket socket) { ConnectToServer = socket; } public void run() { try { DataInputStream inFromClient = new DataInputStream(ConnectToServer.getInputStream()); while (true) { String nghiem = inFromClient.readLine(); System.out.println("" + nghiem); } } catch (IOException e) { System.out.println("Loi" + e); } } } Server package socket; import java.net.*; import java.net.Socket; import java.io.*; public class GiaiPTB2_Server { public static void main(String argv[]) throws IOException

{ ServerSocket ss = new ServerSocket(9999); System.out.println("Hello, wellcome to Server. Waiting.... "); while(true) { Socket s = ss.accept(); GPTB2_Thread t = new GPTB2_Thread(s); t.start(); } } } ServerThread package socket; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.*; import java.net.Socket; public class GPTB2_Thread extends Thread { Socket connectToClient = new Socket(); public GPTB2_Thread(Socket socket) { connectToClient = socket; } public void run() { try { PrintWriter out = null; out = new PrintWriter(connectToClient.getOutputStream(), true); DataInputStream inFromClient = new DataInputStream(connectToClient.getInputStream()); while (true) { String chuoiKq="";

Float a = inFromClient.readFloat(); Float b = inFromClient.readFloat(); Float c = inFromClient.readFloat(); float delta = b * b - 4 * a * c; if (a == 0) if (b == 0) if (c == 0) { chuoiKq = "Phuong trinh co vo so nghiem : \n"; out.println(chuoiKq); } else { chuoiKq = "Phuong trinh vo nghiem :\n"; // outToClient.writeBytes(chuoiKq); out.println(chuoiKq); } else { chuoiKq = "Phuong trinh co nghiem duy nhat: " + c / b + "\n"; out.println(chuoiKq); } else { if (delta < 0) { chuoiKq = "Phuong trinh vo nghiem"; out.println(chuoiKq); } else if (delta > 0) { float x1 = (float) (-b + Math.sqrt(delta)) / (2 * a); float x2 = (float) (-b - Math.sqrt(delta)) / (2 * a); chuoiKq = "phuong trinh co 2 nghiem phan biet x1 =:" + x1 + "\t" + "Va x2 =" + x2 + "\n"; out.println(chuoiKq); } else { chuoiKq = ("Phuong trinh co nghiem kep x1 = x2 = " + (-b / (2 * a)));

out.println(chuoiKq); } } } } catch (IOException ex) { System.err.println(ex); } } } UPPERCASE Client package socket; import java.io.BufferedReader; import java.io.*; import java.net.Socket; public class TCPClient_upcase { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; //Create Socket Socket clientSocket = new Socket("localhost", 9999); //Create inputStream for reading data from keyboard BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in)); sentence=inFromUser.readLine(); // Create OutputStream for writing byte to Server socket DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); outToServer.writeBytes(sentence + '\n'); // Create inputStream for reading data from Serversocket BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); modifiedSentence = inFromServer.readLine(); //View data that received from server System.out.println("FROM SERVER: " + modifiedSentence);

clientSocket.close(); } } Server package socket; import java.io.BufferedReader; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class TCPServer_upcase { public static void main(String argv[]) throws Exception { String clientSentence; String upSentence; System.out.println("Hello, wellcome to Server. Waiting.... "); ServerSocket welcomeSocket = new ServerSocket(9999); while(true) { //Create connection Socket connectionSocket = welcomeSocket.accept(); //Create InputStream for reading data from socket client BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); clientSentence = inFromClient.readLine(); // Create OutputStream for writing data to socket client DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); //Process: upcase upSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(upSentence); System.out.println("Done!!!"); } }

} O CHUI Client package socket; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.Socket; public class BT3_Client { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; Socket clientSocket = new Socket("localhost", 9999); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); sentence = inFromUser.readLine(); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); outToServer.writeBytes(sentence + '\n'); //outToServer.writeUTF(str); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } Server package socket; import java.io.BufferedReader; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket;

public class BT3_Server { public static void main(String argv[]) throws Exception { String clientSentence; String Sentence = ""; int d=0; System.out.println("Hello, wellcome to Server. Waiting.... "); ServerSocket welcomeSocket = new ServerSocket(9999); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); clientSentence = inFromClient.readLine(); // String s = inFromClient.readUTF(); DataOutput outToClient = new DataOutputStream(connectionSocket.getOutputStream()); String [] temp = clientSentence.split(" "); StringBuilder str = new StringBuilder(); for(int i=0;i<temp.length;i++) { if(!"".equals(temp[i])) { d++; StringBuilder s = new StringBuilder(" " + temp[i]); str = s.reverse(); Sentence = Sentence + str.toString(); } } Sentence="So tu:" + d + "\t Chuoi dao: " + Sentence+'\n'; outToClient.writeBytes(Sentence); System.out.println("Done!!!"); connectionSocket.close(); } } }

UDP UPPERCASE Client package UpcaseUDP; import java.awt.*; import java.io.*; import java.net.*; import java.util.logging.Level; import java.util.logging.Logger; public class Client extends java.awt.Frame { public Client() { initComponents(); } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jTextField2 = new javax.swing.JTextField(); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel1.setText("result:"); jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel2.setName("lblkq"); jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel3.setText("Input a String:"); jLabel3.setName("lbl1"); jButton1.setText("send string"); 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(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(jButton1)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(197, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm System.exit(0); }//GEN-LAST:event_exitForm private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton1ActionPerformed // TODO add your handling code here: String str = jTextField2.getText(); try { DatagramSocket clientSk = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] seData= new byte[1024]; byte[] reData = new byte[1024]; seData=str.getBytes(); DatagramPacket sePacket = new DatagramPacket(seData, seData.length, IPAddress, 9876); clientSk.send(sePacket); DatagramPacket rePacket = new DatagramPacket(reData, reData.length); clientSk.receive(rePacket); String modiStr = new String(rePacket.getData()).trim(); jLabel2.setText(modiStr); clientSk.close(); } catch(Exception ex) {} }//GEN-LAST:event_jButton1ActionPerformed public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() {

public void run() { new Client().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables } Server package UpcaseUDP; import com.sun.org.apache.xml.internal.serializer.utils.Messages; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.text.MessageFormat; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; public class server extends javax.swing.JFrame { public server() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel1.setText("Server is waiting...."); jLabel1.setName("lblHienThi"); 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(46, 46, 46) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(58, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(122, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void formWindowOpened(java.awt.event.WindowEvent evt) {//GENFIRST:event_formWindowOpened try { // TODO add your handling code here: DatagramSocket serverSk = new DatagramSocket(9876); byte[] reData = new byte[1024];

byte[] seData = new byte[1024]; while(true) { DatagramPacket rePacket = new DatagramPacket(reData, reData.length); serverSk.receive(rePacket); String sentence = new String(rePacket.getData()); InetAddress IPAddress = rePacket.getAddress(); int port = rePacket.getPort(); String capSentence = sentence.toUpperCase(); seData = capSentence.getBytes(); DatagramPacket sePacket = new DatagramPacket(seData, seData.length, IPAddress, port); serverSk.send(sePacket); JOptionPane.showMessageDialog(this,"Done!!!!!"); } } catch (IOException ex) { Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_formWindowOpened public static void main(String args[]) { 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(server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

} catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new server().setVisible(true); } }); } private javax.swing.JLabel jLabel1; } THREAD Thread m NT package Bai1; import java.lang.Thread; public class ThreadDemNT extends Thread { boolean LaNT(int x) { if(x<2) return false; for(int i=2;i<=x/2;i++) { if(x%i==0) { return false; } } return true; }

int x,y; int d=0; ThreadDemNT(int a, int b) { x = a; y = b; } @Override public void run() { long startTime = System.currentTimeMillis(); for(int i = x; i < y; i++) { if(LaNT(i)==true) { d++; } } long Time = System.currentTimeMillis() - startTime; System.out.println("Thread " + x + " counted " + d + " Evens in " + (Time/1000.0) + " seconds."); } } ThreadSoHoanHao import java.lang.Thread; public class ThreadDemSHH extends Thread { boolean laSHH(int x) { double a = Math.sqrt(x); if((a-(int) a)!=0) return false; return true; } int x,y; int d=0;

public ThreadDemSHH(int x, int y) { this.x = x; this.y = y; } public void run() { long startTime = System.currentTimeMillis(); for(int i = x; i < y; i++) { if(laSHH(i)==true) { d++; } } long Time = System.currentTimeMillis() - startTime; System.out.println("Thread " + x + " counted " + d + " Evens in " + (Time/1000.0) + " seconds."); } } Main package Bai1; import java.lang.Thread; import java.util.Scanner; public class Main { public static void main(String[] args) throws InterruptedException { Scanner TextIO = new Scanner (System.in); int numThreads; int n; System.out.print("Nhap N: "); n=TextIO.nextInt(); System.out.print("Input threads: "); numThreads=TextIO.nextInt(); System.out.print("\nCreating" + numThreads + " Even-counting threads..."); /*ThreadDemNT[] worker = new ThreadDemNT[numThreads];

for(int i = 0; i < numThreads; i++) { int temp=n/numThreads; worker[i]=new ThreadDemNT(i*temp, (i+1)*temp); worker[i].start(); }*/ ThreadDemSHH[] worker = new ThreadDemSHH[numThreads]; for(int i = 0; i < numThreads; i++) { worker[i]=new ThreadDemSHH(0, n); worker[i].start(); } } }

Anda mungkin juga menyukai