Main Class
public class Main
{
public static void main(String[] args) throws Exception
{
new ChatGUI().setVisible(true);
UDPServer myServer = new UDPServer();
UDPClient myClient = new UDPClient();
myServer.start();
myClient.start();
}
}
Client Class
import java.net.*;
import java.io.*;
import java.util.Random;
public class UDPClient extends Thread
{
ChatGUI gui;
// The key for 'encrypting' and 'decrypting'.
static final String key = "Encrypt";
//Simulate packet loss rate
private static final double LOSS_RATE = 0.3;
public static String encryptString(String str)
{
StringBuffer sb = new StringBuffer (str);
int lenStr = str.length();
int lenKey = key.length();
// For each character in our string, encrypt it...
for ( int i = 0, j = 0; i < lenStr; i++, j++ )
{
if ( j >= lenKey ) j = 0; // Wrap 'round to beginning of key string.
// XOR the chars together. Must cast back to char to avoid compile error.
sb.setCharAt(i, (char)(str.charAt(i) ^ key.charAt(j)));
}
return sb.toString();
}
public void run()
{
//create random number generator for use in simulated packet loss.
Random random = new Random();
try
{
// Specify size of UDP chunk to send
byte[] send_data = new byte[1024];
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));//Create input stream
DatagramSocket client_socket = new DatagramSocket(); //Create a client socket
InetAddress IPAddress = InetAddress.getByName("localhost"); //Translate hostname to IP address using dns
while (true)
{
System.out.println("Type Something (q or Q to quit): ");
String data = inFromUser.readLine();
//String s1 = data;
data = encryptString(data);
if (data.equals("q") || data.equals("Q"))
break;
else
{
send_data = data.getBytes();
//Create datagram packet with data-to-send, length, IP address, port
DatagramPacket send_packet = new DatagramPacket(send_data,
send_data.length,
IPAddress, 5002);
// Decide whether to reply, or simulate packet loss.
if (random.nextDouble() < LOSS_RATE) {
System.out.println("Message not sent.");
System.out.println("Attempting to resend.");
System.out.println("Successfully resent," + "You wrote: " + data);
client_socket.send(send_packet);
}
else
//Send datagram to server
client_socket.send(send_packet);
System.out.println("You wrote: " + data);
gui.setTexter("Hello");
gui.setLabel("Hello");
}
}
client_socket.close();
System.exit(0);
}
catch (Exception e)
{
System.out.println("Error1" + e);
}
}
}
Server Class
import java.net.*;
import java.util.Random;
//import java.io.*;
public class UDPServer extends Thread
{
public void run()
{
int measure;
// Specify size of UDP chunk to receive
byte[] receive_data = new byte[1024];
try
{
//Create a datagram socket at port
DatagramSocket server_socket = new DatagramSocket(5001);
System.out.println ("UDPServer Waiting for client");
while(true)
{
//Create the space for received datagram
DatagramPacket receive_packet = new DatagramPacket(receive_data,
receive_data.length);
//Receive the datagram
server_socket.receive(receive_packet);
String data = new String(receive_packet.getData(),0
,receive_packet.getLength());
String s1 = data;
data = UDPClient.encryptString(s1);
measure = receive_packet.getLength();
//Get the IP address from the sender
InetAddress IPAddress = receive_packet.getAddress();
if (data.equals("q") || data.equals("Q"))
break;
else
System.out.println("( " + IPAddress + " , " +
measure + " ) They said :" + data );
}
}
catch(Exception e)
{
System.out.println("Error2" + e);
}
}
}
ChatGUI
public class ChatGUI extends javax.swing.JFrame {
/**
* Creates new form ChatGUI
*/
public ChatGUI() {
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();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("jTextField1");
jLabel1.setText("jLabel1");
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.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(160, 160, 160)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(78, 78, 78)
.addComponent(jLabel1)))
.addContainerGap(181, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(87, 87, 87)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 124, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55))
);
pack();
}// </editor-fold>
/**
* @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(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatGUI.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 ChatGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
public void setTexter(String s ) { // the setter method to set text of "jTextField1"
jTextField1.setText(s);
}
public void setLabel(String s ) { // the setter method to set text of "jTextField1"
jLabel1.setText(s);
}
}

New Topic/Question
Reply



MultiQuote






|