多线程多客户编程

时间:2009-09-04 05:00:53

标签: java multithreading

我正在做一个客户端 - 服务器应用程序。 我想用一台服务器连接多个客户端。这里每个客户端使用三个端口与服务器连接:

  • 首先 - 发送图像
  • 第二 - 发送键盘事件
  • 第三 - 发送鼠标事件

所有这些信息都发送到服务器,但它在多线程中产生问题。如果我使用单线程,那就没关系,但是在多线程的情况下,由于多个端口而产生问题。 请任何人都可以给我解决方案。

感谢

客户代码:

    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    import java.awt.Robot.*;
    class Client extends JFrame
    {
        //  port no 143 for sending images...
        //  port no 321 for recieving mouseEvents...
        //  port no 678 for recieving keyEvents...

        public static void main(String args[])
        {
            new Client();
        }

    /*-----------------------------for Establish Connection------------------*/
        Client()
        {
            super("10.1.8.123");

            setTitle("10.1.8.123");
            System.out.println("waiting for permission..");
            try
            {
                ServerSocket s=new ServerSocket(112);
                Socket socket=s.accept();

                Thread.sleep(0,1);

            }

            catch(Exception e)
            {}

            setVisible(false);

            new ImageSender();
            new MouseEventsReceiver();
            new KeyboardEventsReceiver();
        }
    }
    /*--------------------------------------------------------------------------*/

    class ImageSender implements Runnable
    {       

        ImageSender()
        {
            Thread t=new Thread(this);
            t.start();
        }

    /*----------------------------------For capture the screen-------------------*/
        public void run()
        {
            try
            {
                Robot r=new Robot();
                Toolkit t=Toolkit.getDefaultToolkit();
                Rectangle rect=new Rectangle(t.getScreenSize());
                while(true)
                {
                    Socket s=new Socket("10.1.8.107",112);          
                    OutputStream out=s.getOutputStream();
                    ObjectOutputStream oos=new ObjectOutputStream(out);
                    BufferedImage b_img=r.createScreenCapture(rect);
                    ImageIcon img=new ImageIcon(b_img);
                    oos.writeObject(img);

                    Thread.sleep(100);

                    oos.close();    
                    out.close();
                }
            }
            catch(Exception e)
            {
                System.out.println("in ImageSender:"+e);
            }
        }
    }
    /*-----------------------------------------------------------------------------*/   

    class MouseEventsReceiver implements Runnable
    {
        MouseEventsReceiver()
        {
            Thread t=new Thread(this);
            t.start();
        }
        public void run()
        {
            System.out.println("inside run....");

            try
            {
                ServerSocket s=new ServerSocket(113);   //must be outside while()...            
                Robot r=new Robot();
                while(true)
                {
                    System.out.println("Socket created at port 321");
                //  ServerSocket s=new ServerSocket(321);

                    Socket client=s.accept();
                    System.out.println("after accept...");

                    InputStream in=client.getInputStream();
                    ObjectInputStream ois=new ObjectInputStream(in);

                    MouseEvents m=(MouseEvents)ois.readObject();
                    System.out.println("Mouse Event Received X="+m.getX());

                    System.out.println("button:="+m.getButton());

                    r.mouseMove(m.getX(),m.getY());
                    if(m.getButton()==1)
                    {
                        r.mousePress( InputEvent.BUTTON1_MASK);
                        r.mouseRelease(InputEvent.BUTTON1_MASK);

                    }
                    else if(m.getButton()==2)
                    {
                        r.mousePress( InputEvent.BUTTON2_MASK);
                        r.mouseRelease(InputEvent.BUTTON2_MASK);
                    }
                    else if(m.getButton()==3)
                    {
                        r.mousePress( InputEvent.BUTTON3_MASK);
                        r.mouseRelease(InputEvent.BUTTON3_MASK);
                    }
                    else            
                    {
                    }           

                    ois.close();
                    in.close();
                }

            }
            catch(Exception e)
            {
                System.out.println("in mouseEvent Reciever:"+e);
            }
        }
    }
    /*-----------------------------------------------------------------------------*/
    class KeyboardEventsReceiver implements Runnable
    {
        KeyboardEventsReceiver()
        {
            Thread t=new Thread(this);
            t.start();
        }
        public void run()
        {
            System.out.println("in keyboard run...");

            try
            {
                Robot r=new Robot();
                ServerSocket s=new ServerSocket(114);   //must be outside while()...        

                while(true)
                {
                //  ServerSocket s=new ServerSocket(678);           

                    Socket client=s.accept();
                    InputStream in=client.getInputStream();
                    ObjectInputStream ois=new ObjectInputStream(in);
                    KeyboardEvents k=(KeyboardEvents)ois.readObject();
                    System.out.println("Key Received:"+k.getKeyChar());
                    r.keyPress((char)k.getKeyChar());
                //  r.keyPress(97);

                    ois.close();
                    in.close();
                }
            }
            catch(Exception e)
            {
                System.out.println("inside Key board events.."+e);
            }
        }
    }

服务器代码:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;

    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.UIManager;

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


    public class Menu extends JFrame 
    {
        public String ip1="10.1.8.106";
        public String ip2="10.1.8.108";
        public String ip3="10.1.8.109";
        public int port=111;
        public int i;


        public Menu() 
        {

            setTitle("Server");

            JMenuBar menubar = new JMenuBar();

            JMenu file = new JMenu("File");
            file.setMnemonic(KeyEvent.VK_F);

            JMenuItem client1 = new JMenuItem("clt1");
            JMenuItem client2 = new JMenuItem("clt2");
            JMenuItem client3 = new JMenuItem("clt3");

            client1.setMnemonic(KeyEvent.VK_F1);
            client2.setMnemonic(KeyEvent.VK_F2);
            client3.setMnemonic(KeyEvent.VK_F3);

            client1.setToolTipText("Client1 selected");
            client2.setToolTipText("Client2 selected");
            client3.setToolTipText("Client3 selected");

            client1.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent event) 
                {
                        new Screen(ip1,port);
                }
            });

                client2.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent event) 
                {
                //  port=port+3;
                    new Screen(ip2,port+3);
                }
            });

                client3.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent event) 
                {
                //  port=port+3;
                    new Screen(ip3,port+6);
                }
            });


            file.add(client1);
            file.add(client2);
            file.add(client3);

            menubar.add(file);

            setJMenuBar(menubar);

            setSize(250, 200);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setVisible(true);
        }

        public static void main(String[] args) 
        {

            new Menu();

        }
    }
    class Screen extends JFrame
    {
        //  port no 143 for receiving images...
        //  port no 321 for sending mouseEvent...
        //  port no 678 for sending keyEvents...

        final JFrame frame;

    /*  public static void main(String args[])
        {
            new Screen();
        }*/
        Screen(String ip,int port)
        {
            super("Remote Access Server");
            frame=this;
            try
            {
            //  port=port+1;
                Socket s=new Socket(ip,port+1);

                Thread.sleep(0,1);
            }
            catch(Exception e)
            {}
            new ImageReceiver(frame,ip,port);

            setVisible(true);
        }
    }

    /*------------------------------------------------------------------------------------*/

    class ImageReceiver extends Window implements Runnable,MouseListener,MouseMotionListener,KeyListener
    {
            String ipadd;
            int port1;
        ImageReceiver(Frame f,String ip,int port)
        {
            super(f);
            ipadd=ip;
            port1=port;
            addMouseListener(this);
            addMouseMotionListener(this);   //f not reqrd bcoz its done on window...
            f.addKeyListener(this);     //f is required for clicking on frames....

            f.requestFocus();   // must required ...

            Toolkit toolkit=Toolkit.getDefaultToolkit();
            setSize(toolkit.getScreenSize());

            setVisible(true);

            Thread t=new Thread(this);
            t.start();
        }
        public void run()
        {
            try
            {
                ServerSocket s=new ServerSocket(port1+1);
                while(true)
                {
                    Socket socket=s.accept();
                    setBackground(Color.black);
                    InputStream in=socket.getInputStream();
                    ObjectInputStream ois=new ObjectInputStream(in);
                    ImageIcon img=(ImageIcon)ois.readObject();
                    Graphics g=getGraphics();
                    img.paintIcon(this,g,0,0);
                }
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }
        /*--------------------------mouse events...----------------------------------------*/
        public void mouseClicked(MouseEvent m)
        {
            System.out.println("mouse clicked");
            sendPacket(new MouseEvents(m.getX(),m.getY(),m.getButton()));
        }
        public void mousePressed(MouseEvent m)
        {
        }
        public void mouseReleased(MouseEvent m)
        {
        }
        public void mouseEntered(MouseEvent m)
        {
        }
        public void mouseExited(MouseEvent m)
        {
        }
        public void mouseMoved(MouseEvent m)
        {
            sendPacket(new MouseEvents(m.getX(),m.getY()));

        }

        public void mouseDragged(MouseEvent m)
        {
    //      sendPacket(new MouseEvents(m.getX(),m.getY(),m.getButton()));
        }

        private void sendPacket(MouseEvents m)
        {
            try
            {
            //  port1=port1+1;
                Socket s=new Socket(ipadd,port1+2);
                OutputStream out=s.getOutputStream(); 
                ObjectOutputStream oos=new ObjectOutputStream(out);
                oos.writeObject(m);
                oos.close();
                s.close();
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }

        /*---------------------------keyboard events...-----------------------------------------------*/
        //all the events are required to be included.....+requestFocus() is also must...    

        public void keyPressed(KeyEvent k)
        {
            System.out.println("after key pressed...");
            sendKeyPacket(new KeyboardEvents(k.getKeyCode()));      
        }
        public void keyReleased(KeyEvent k)
        {
            System.out.println("after key released...");
            sendKeyPacket(new KeyboardEvents(k.getKeyCode()));

        }
        public void keyTyped(KeyEvent k)
        {
            System.out.println("after key typed..."+k.getKeyChar());
            sendKeyPacket(new KeyboardEvents(k.getKeyChar()));

        }


        private void sendKeyPacket(KeyboardEvents k)
        {
            try
            {
            //  port1=port1+1;
                Socket s=new Socket(ipadd,port1+3);
                OutputStream out=s.getOutputStream(); 
                ObjectOutputStream oos=new ObjectOutputStream(out);
                oos.writeObject(k);
                oos.close();
                s.close();
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }


    }

2 个答案:

答案 0 :(得分:0)

我们需要更多的事情继续下去:

case of multithread it creates problem due to the multiple ports

你看到了什么问题?

答案 1 :(得分:0)

你也可以使用UDP和TCP作为不同的连接,并为套接字连接保持这个...

如果你同时保持UDP和TCP连接,那么很容易发送数据包并通过端口建立套接字..

你是正确的,但你需要修改一些小改动...... gud继续保持这种方式是你的方式是ri8

还有一件事,如果您要使用多线程,那么您必须非常了解线程管理和同步。