This is code java i need to send numbers ( n number(infinety)) to the server and
ID: 3695977 • Letter: T
Question
This is code java
i need to send numbers ( n number(infinety)) to the server and client return max and min number
The client send to server infinty numbers for example (9 , 100 , 50 )
The server will return to the client the max and min number.
the output from server to client :
the min number:9
the max number:100
------------------------------
Server : //
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package suliman;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import static suliman.Client.txtField;
/**
*
* @author ^_^
*/
public class Server extends javax.swing.JFrame {
static ServerSocket server;
static Socket socket;
static DataInputStream input;
static DataOutputStream output;
/**
* Creates new form Server
*/
public Server() {
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() {
messag = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txtField = new javax.swing.JTextArea();
send = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
txtField.setColumns(20);
txtField.setRows(5);
jScrollPane1.setViewportView(txtField);
send.setText("Send");
send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tekton Pro Cond", 1, 36)); // NOI18N
jLabel1.setText("Server");
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(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(messag)
.addGap(18, 18, 18)
.addComponent(send, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(150, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(132, 132, 132))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(4, 4, 4)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(send, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)
.addComponent(messag))
.addContainerGap())
);
pack();
}// </editor-fold>
private void sendActionPerformed(java.awt.event.ActionEvent evt) {
try {
String message="";
message=messag.getText().toString();
output.writeUTF(message);
output.flush();
txtField.setText(txtField.getText()+" "+"You: "+message);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @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);
}
});
String message="";
try {
server=new ServerSocket(4444);
// txtField.setText(txtField.getText()+" "+"Server is Running....");
socket=server.accept();
// txtField.setText(txtField.getText()+" "+"Client is Connected ^_^");
input=new DataInputStream(socket.getInputStream());
output=new DataOutputStream(socket.getOutputStream());
while(true)
{
message=input.readUTF();
txtField.setText(txtField.getText()+" "+"Client: "+message);
}
} catch (Exception e) {
System.out.println(e);
}
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextField messag;
private javax.swing.JButton send;
public static javax.swing.JTextArea txtField;
// End of variables declaration
}
--------------------------
Client : //
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package suliman;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static suliman.Server.input;
import static suliman.Server.messag;
import static suliman.Server.txtField;
/**
*
* @author Eslam
*/
public class Client extends javax.swing.JFrame {
static Socket client;
static DataInputStream input;
static DataOutputStream output;
public Client() {
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();
jScrollPane1 = new javax.swing.JScrollPane();
txtField = new javax.swing.JTextArea();
send = new javax.swing.JButton();
masseg = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tekton Pro Cond", 1, 36)); // NOI18N
jLabel1.setText("Client");
txtField.setColumns(20);
txtField.setRows(5);
jScrollPane1.setViewportView(txtField);
send.setText("Send");
send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendActionPerformed(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(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(masseg)
.addGap(18, 18, 18)
.addComponent(send, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(150, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(132, 132, 132))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(send, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)
.addComponent(masseg))
.addContainerGap())
);
pack();
}// </editor-fold>
private void sendActionPerformed(java.awt.event.ActionEvent evt) {
try {
String message="";
message=masseg.getText().toString();
output.writeUTF(message);
output.flush();
txtField.setText(txtField.getText()+" "+"You: "+message);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
/* 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(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);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Client().setVisible(true);
}
});
client=new Socket("127.0.0.1",4444);
input=new DataInputStream(client.getInputStream());
output=new DataOutputStream(client.getOutputStream());
String message="";
while(true)
{
message=input.readUTF();
txtField.setText(txtField.getText().toString()+" "+"Server: "+message);
System.out.println(message);
}
} catch (UnknownHostException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextField masseg;
private javax.swing.JButton send;
public static javax.swing.JTextArea txtField;
// End of variables declaration
}
Explanation / Answer
Following is the Client server code which is to be run in netbeans.
First create desktop Application project with the name desktopapplication1 and following two files
AppServer.java and AppClient.java.
AppServer.Java Code is given below
package desktopapplication1;
/**
*
* @author Nitesh
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
public class AppServer extends Frame implements ActionListener,Runnable
{
//Declarations
Button b1;
TextField tf;
TextArea ta;
ServerSocket ss;
Socket s;
String output;
PrintWriter pw;
BufferedReader br;
Thread th;
public AppServer()
{
Frame f=new Frame("Server Side Chatting");//Frame for Server
f.setLayout(new FlowLayout());//set layout
f.setBackground(Color.orange);//set background color of the Frame
b1=new Button("Send");//Send Button
b1.setBackground(Color.pink);
b1.addActionListener(this);//Add action listener to send button.
tf=new TextField(15);
ta=new TextArea(12,20);
ta.setBackground(Color.cyan);
f.addWindowListener(new W1());//add Window Listener to the Frame
f.add(tf);//Add TextField to the frame
f.add(b1);//Add send Button to the frame
f.add(ta);//Add TextArea to the frame
try{
ss=new ServerSocket(12000);//Socket for server
s=ss.accept();//accepts request from client
System.out.println(s);
//below line reads input from InputStreamReader
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
//below line writes output to OutPutStream
pw=new PrintWriter(s.getOutputStream(),true);
}catch(Exception e)
{
}
th=new Thread(this);//start a new thread
th.setDaemon(true);//set the thread as demon
th.start();
setFont(new Font("Arial",Font.BOLD,20));
f.setSize(200,200);//set the size
f.setLocation(300,300);//set the location
f.setVisible(true);
f.validate();
}
//method required to close the Frame on clicking "X" icon.
private class W1 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
//This method will called after clicking on Send button.
public void actionPerformed(ActionEvent ae)
{
pw.println(output);//write the value of textfield into PrintWriter
//tf.setText("");//clean the textfield
}
//Thread running as a process in background
public void run()
{
while(true)
{
try{
String str=br.readLine();//reads the input from textfield
int numbers,max=0,min=50000;
StringTokenizer st = new StringTokenizer(str," ");
while (st.hasMoreTokens()) {
String str1 = st.nextToken();
numbers=Integer.parseInt(str1);
if (numbers>max)
max=numbers;
if(numbers<min)
min=numbers;
///System.out.println(st.nextToken());
}
output="max number is "+ max +"min number is "+ min ;
ta.append(str+" ");//Append to TextArea
}catch(Exception e)
{
}
}
}
//Main method
public static void main(String args[])
{
//Instantiate AppServer class
AppServer server = new AppServer();
}
}
AppClient.java Code is given below
package desktopapplication1;
/**
*
* @author Nitesh
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class AppClient extends Frame implements ActionListener,Runnable
{
//Declarations
Button b;
TextField tf;
TextArea ta;
Socket s;
PrintWriter pw;
BufferedReader br;
Thread th;
public AppClient()
{
Frame f=new Frame("Client Side Chatting");//Frame for Client
f.setLayout(new FlowLayout());//set layout
f.setBackground(Color.orange);//set background color of the Frame
b=new Button("Send");//Send Button
b.addActionListener(this);//Add action listener to send button.
f.addWindowListener(new W1());//add Window Listener to the Frame
tf=new TextField(15);
ta=new TextArea(12,20);
ta.setBackground(Color.cyan);
f.add(tf);//Add TextField to the frame
f.add(b);//Add send Button to the frame
f.add(ta);//Add TextArea to the frame
try{
s=new Socket(InetAddress.getLocalHost(),12000);//Socket for client
//below line reads input from InputStreamReader
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
//below line writes output to OutPutStream
pw=new PrintWriter(s.getOutputStream(),true);
}catch(Exception e)
{
}
th=new Thread(this);//start a new thread
th.setDaemon(true);//set the thread as demon
th.start();
setFont(new Font("Arial",Font.BOLD,20));
f.setSize(200,200);//set the size
f.setVisible(true);
f.setLocation(100,300);//set the location
f.validate();
}
//method required to close the Frame on clicking "X" icon.
private class W1 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
//This method will called after clicking on Send button.
public void actionPerformed(ActionEvent ae)
{
pw.println(tf.getText());//write the value of textfield into PrintWriter
tf.setText("");//clean the textfield
}
//Thread running as a process in background
public void run()
{
while(true)
{
try{
ta.append(br.readLine()+" ");//Append to TextArea
}catch(Exception e) {}
}
}
//Main method
public static void main(String args[])
{
//Instantiate AppClient class
AppClient client = new AppClient();
}
}
After copying the above code you will have to right cllick on the server file and click on run
After that right click on client file and run it.
Now you will see two small windows.
In the client window you will see text box besides on send button. In this button you have to give numbers with space in between. After that you have to click on send.
Now, click on send button present in server window.
You will get your answer in text area below send button in client window
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.