الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

client and server code

مغلق
بدأه دلوعة الجافا في 10 مارس 2006 · 10 رد · 1,330 مشاهدة · في JavaSE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

السلام عليكم ورحمة الله و بركاته

اهلين اخواني

اريد احد يساعدني "client and server code"

الكود انا سويته بس بقى لي هذا البارت ما عرفت كيف اسويه و الي اهو

* Extend both client and server program to use multiple send/receive by using loops. The exit condition should be message “Bye” send by client.

كتبت الكود client و ال اهو

import java.io.*;
import java.net.*;

public class ChatClient{
	public static void main(String [] args){
  String text =null;
  byte [] buff = null;
  String name = "Client>";
  DatagramPacket dataPacket = null;

  if(args.length == 0){
   	 System.out.println("Syntax Error:  expecting [hostname]");
   	 return;
  }
  try{
 	 //1. create a datagram socket
 	 DatagramSocket cs = new DatagramSocket();
 	 System.out.print(name);
 	 //2. accepting the data from keyboard and prepare the buff
 	 InputStream keyboard = System.in;
 	 InputStreamReader reader = new InputStreamReader(keyboard);

 	 BufferedReader bufReader= new BufferedReader(reader);
 	 text = name + bufReader.readLine();
 	 buff = text.getBytes();

 	 //3.creating datagram packet with data
 	 dataPacket = new DatagramPacket(buff,buff.length,
         	 InetAddress.getByName(args[0]),2001);
 	 //4. sending the datagram packet through the socket
 	 cs.send(dataPacket);

 	 //5. closing
 	 cs.close();
  }catch(IOException ioe){
 	 System.err.println("IO ERROR: " + ioe);
  }
	}//main
}//class

و كود server

import java.io.*;
import java.net.*;

public class ChatServer{
	public static void main(String [] args){
  DatagramSocket ss = null;
  DatagramPacket req_packet = null;

  //1. create the datagram socket with spcific port
  try{
 	 ss = new DatagramSocket(2001);
  }catch(SocketException se){
 	 System.err.println("ERROR :" + se);
  }
  try{
 	 //2. create empty datagram packet
 	 req_packet = new DatagramPacket(new byte[100],100);
 	 //setting the time
 	 ss.setSoTimeout(5 * 1000);
 	 try{
    // 3. receive the packet
    ss.receive(req_packet);

 	 //4. display the packet inforamtion in the screen
 	 /* ways of creating strings
 	 String d = "dksjfl";
 	 String d = new String("dss");
 	 */
    String data = new String (req_packet.getData());
    System.out.println(data);
 	 }catch(InterruptedIOException ioe){
    System.out.println("Timeout");
    return;
 	 }
  }catch(IOException ioe){
 	 System.err.println("can't receive packet");
  }
	}//main
}//class

اتمنى اشوف ردكم

و شكرا

#2

بلييييييييييز ساعدوني محتاجه مساعدتكم

#3

انتظر ردكم

اتمنى احد يساعدني

#4

بس لو ممكن توضيح المقصود بـ

* Extend both client and server program to use multiple send/receive by using loops. The exit condition should be message “Bye” send by client

يعني تراسل نص فقط ؟؟

منقطع من حين لاخر

#5

نعم

#6

السلام عليكم

رامي العيساوي ممكن مساعده

اريد اعرف كيف اسوي Terminating the connection

وين اكتب كلمة BYE

in server side

can you help me

تم تعديل هذه المشاركة بواسطة دلوعة الجافا في 12 مارس 2006 في 21:15

#7

كود السيرفر كالتالي

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class Server extends JFrame {
   
   ServerSocket server;
   Socket connection;
   ObjectOutputStream output;
   ObjectInputStream input;
   JTextArea area;
   JScrollPane scroll;
   JTextField f;
   
   
    public Server()
    {
        super("Server..");
        Container c=getContentPane();
        
        area=new JTextArea();
        scroll=new JScrollPane(area);
        area.setEditable(false);
        area.setBackground(Color.PINK);
        c.add(scroll);
        
        
        f=new JTextField();
        f.addActionListener(
       	 new ActionListener()
       	 {
          public void actionPerformed(ActionEvent e)
          {
         	 sendData(f.getText());
          }
       	 });
       	 
        c.add(f,BorderLayout.SOUTH);	
        setLocation(300,150);
        setSize(300,300);
        
        
    }

   // set up and run server 
   public void runServer()
   {
      // set up server to receive connections; process connections
      try {

         // Step 1: Create a ServerSocket.
         server = new ServerSocket( 12345, 100 );

         

            try {
               waitForConnection(); // Step 2: Wait for a connection.
               getStreams();     // Step 3: Get input & output streams.
               while ( true ) {
               processConnection(); // Step 4: Process connection.
            }}

            // process EOFException when client closes connection 
            catch ( EOFException eofException ) {
               System.err.println( "Server terminated connection" );
            }

      } // end try

      // process problems with I/O
      catch ( IOException ioException ) {
         ioException.printStackTrace();
      }

   } // end method runServer
    
    public void waitForConnection() throws IOException
    {
  area.append("\nWait For Connection ");
   	 connection=server.accept();
   	 area.append("\nClient"+connection.getInetAddress().getHostName());

    }
    
    public void getStreams()throws IOException
    {
   	 output=new ObjectOutputStream(connection.getOutputStream());
   	 output.flush();
   	 
  input=new ObjectInputStream(connection.getInputStream());
    }
    
    public void processConnection() throws IOException
    {
   	 String s="";
   	 try{
      s=(String) input.readObject();
      if(s.equals("END"))
      {
     	 JOptionPane.showMessageDialog(this,"Client terminate");
     	 closeConnection();
       	 }
       	 else
      area.append("\nClient >>"+s);
      }
      catch(ClassNotFoundException ex){}
    }
    
    public void closeConnection()
    {
   	 try{
      input.close();
      output.close();
      connection.close();
   	 }
   	 catch(IOException e){}
    }
    
    public void sendData(String s)
    {
   	 try{
      area.append("\n"+"Server >>"+s);
       	 output.writeObject(s);
      output.flush();
      }
      catch(IOException e){}
    }
    
    public static void main(String args[])
    {
        Server a=new Server();
        a.show();
        a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        a.runServer();
    }
}

اما الكلينت :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class Client extends JFrame {
   
   String name;
   Socket client;
   ObjectOutputStream output;
   ObjectInputStream input;
   JTextArea area;
   JScrollPane scroll;
   JTextField f;
   
   
    public Client(String host)
    {
        super("Client..");
        Container c=getContentPane();
        
        name=host;
        
        area=new JTextArea();
        scroll=new JScrollPane(area);
        area.setEditable(false);
        area.setBackground(Color.PINK);
        c.add(scroll);
        
        f=new JTextField();
        f.addActionListener(
       	 new ActionListener()
       	 {
          public void actionPerformed(ActionEvent e)
          {
         	 sendData(f.getText());
          }
       	 });
       	 
        c.add(f,BorderLayout.SOUTH);
        
        setLocation(300,150);
        setSize(300,300);

    }
    
    void runClient()
    {
   	 try{
       	 connectToServer();//1 
       	 getStreams();
        
        
       	 while(true)  //2
       	 processConnection(); //3
       	 
       	 }
       	 catch(IOException ex)
       	 {JOptionPane.showMessageDialog(this,ex.toString());}
    }
   
    void connectToServer() throws IOException
    {
   	 client=new Socket(InetAddress.getByName(name),12345);
   	 area.append("\nConnect to"+client.getInetAddress().getHostName());
    }
    
    void getStreams() throws IOException
    {
   	 output=new ObjectOutputStream(client.getOutputStream());
   	 output.flush();
  input=new ObjectInputStream(client.getInputStream());
    }
    
    public void processConnection() throws IOException
    {
   	 String s="";
   	 try{
      s=(String) input.readObject();
      if(s.equals("END"))
      {
     	 JOptionPane.showMessageDialog(this,"Server terminate");
     	 closeConnection();
       	 }
       	 else
      area.append("\nServer >>"+s);
      }
      catch(ClassNotFoundException ex){}
      
    }
    
    void closeConnection() 
    {
   	 try{
   	 
  input.close();
  output.close();
  client.close();}
  catch(IOException e){}
    }
    
    void sendData(String s)
    {
   	 area.append("\nClient>>"+s);
   	 try{
      output.writeObject(s);
   	 }
   	 catch(IOException e){}
    }
    public static void main(String args[])
    {
        Client a;
        if(args.length==0) a=new Client ("127.0.0.1");
  else a =new Client(args[0]);

        a.show();
        a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        a.runClient();
    }
}

ملاحظة الاتصال ينتهي اذا استقبل الكلينت او السيرفر كلمة END

منقطع من حين لاخر

#8

ممكن اعرف ويش عمل هذا البرنامج

#9

مشكور اخويه ما قصرت

الله يجزيك الف خير

اما بنسبه لسؤال اختي فقيرة علم

هذا الكود تقريبا مثل الشات

تم تعديل هذه المشاركة بواسطة دلوعة الجافا في 13 مارس 2006 في 17:35

#10

اخويه انا شفت الكود الي انت مسونه بس انا مو جذا الي ابيه

انا كتبت الكود بس اريد client and server chat with each other by write in keyboard and when each of them press ctrl C it exit

the server code is

import java.io.*;
import java.net.*;

public class ChatServer{
	public static void main(String [] args){
  DatagramSocket ss = null;
  DatagramPacket req_packet = null;

  //1. create the datagram socket with spcific port
  try{
 	 ss = new DatagramSocket(2001);
  }catch(SocketException se){
 	 System.err.println("ERROR :" + se);
  }
  try{
 	 //2. create empty datagram packet
 	 req_packet = new DatagramPacket(new byte[100],100);
 	 //setting the time
 	 ss.setSoTimeout(5 * 1000);
 	 try{
    // 3. receive the packet
    ss.receive(req_packet);

 	 //4. display the packet inforamtion in the screen
 	 /* ways of creating strings
 	 String d = "dksjfl";
 	 String d = new String("dss");
 	 */
    String data = new String (req_packet.getData());
    System.out.println(data);
 	 }catch(InterruptedIOException ioe){
    System.out.println("Timeout");
    return;
 	 }
  }catch(IOException ioe){
 	 System.err.println("can't receive packet");
  }
	}//main
}//class

the client code:

import java.io.*;
import java.net.*;

public class ChatClient{
	public static void main(String [] args){
  String text =null;
  byte [] buff = null;
  String name = "Client>";
  DatagramPacket dataPacket = null;

  if(args.length == 0){
   	 System.out.println("Syntax Error:  expecting [hostname]");
   	 return;
  }
  try{
 	 //1. create a datagram socket
 	 DatagramSocket cs = new DatagramSocket();
 	 System.out.print(name);
 	 //2. accepting the data from keyboard and prepare the buff
 	 InputStream keyboard = System.in;
 	 InputStreamReader reader = new InputStreamReader(keyboard);

 	 BufferedReader bufReader= new BufferedReader(reader);
 	 text = name + bufReader.readLine();
 	 buff = text.getBytes();

 	 //3.creating datagram packet with data
 	 dataPacket = new DatagramPacket(buff,buff.length,
         	 InetAddress.getByName(args[0]),2001);
 	 //4. sending the datagram packet through the socket
 	 cs.send(dataPacket);

 	 //5. closing
 	 cs.close();
  }catch(IOException ioe){
 	 System.err.println("IO ERROR: " + ioe);
  }
	}//main
}//class

يعني المطلوب

type any text in the client window and type a replay in the server window and the chatting application can go forever unless timeout is raised or Ctrl + C is typed in both sides.

و اتمنى فهمت شنو الي انا ابي اسويه

و شكرا

#11

بلييييز احد يرد على سؤالي

i am wait for replay

هذا الموضوع مغلق.

مواضيع مشابهة