如何使用java将两个客户端套接字保持在一起

时间:2018-04-11 13:59:29

标签: java sockets

我想创建一个类,它包含两个用于client1的套接字I.e套接字和用于客户端2的套接字,以便它们可以一起聊天。 我怎么能实现这一点。当我运行上面的代码时,我得到流损坏的异常。     我的聊天无效。有人可以帮助我吗?

Here is my code .

这是用于发出套接字请求的客户端代码      Client.java

    package customChat;


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


    public class Client
    {

        private String notif = " *** ";

        private ObjectInputStream sInput;       
        private ObjectOutputStream sOutput;     
        private Socket socket;                  

        private String server, username;    
        private int port;                   

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        private RemoteAccess access;

        Client(String server, int port,RemoteAccess access ) {
            this.server = server;
            this.port = port;
            this.access = access;
        }


        public boolean start() 
        {

            try
            {

                socket = new Socket(server, port);
            } 
            catch(Exception ec) {
                display("Error connectiong to server:" + ec);
                return false;
            }

            String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
            display(msg);

            try
            {

                    sInput= new ObjectInputStream(socket.getInputStream());


                    sOutput = new ObjectOutputStream(socket.getOutputStream());


            }
            catch (IOException eIO) {
                eIO.printStackTrace();
                display("Exception creating new Input/output Streams in client: " + eIO);
                return false;
            }

            new ListenFromServer().start();


            try
            {
                sOutput.writeObject(access);
            }
            catch (IOException eIO) {
                display("Exception doing login : " + eIO);
                //disconnect();
                return false;
            }

            return true;
        }


        private void display(String msg) 
        {

            System.out.println(msg);

        }



        void sendMessage(RemoteAccess msg) 
        {
            try 
            {
                System.out.println("I am writing for :"+msg.getTo()+": msg "+msg.getMsg());
                sOutput.writeObject(msg);
            }
            catch(IOException e) {
                display("Exception writing to server: " + e);
            }
        }


        private void disconnect() {
            try { 
                if(sInput != null) sInput.close();
            }
            catch(Exception e) 
            {
                e.printStackTrace();
            }
            try {
                if(sOutput != null) sOutput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            try{
                if(socket != null) socket.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }

        }

        public static void sendFile()
        {

            int portNumber          = 1502;
            String serverAddress    = "localhost";
            Scanner scan            = new Scanner(System.in);

            System.out.println("Enter from ");
             long from          =   scan.nextLong();
            System.out.println("Enter to");
             long to            =   scan.nextLong();

            RemoteAccess access     =   new RemoteAccess(to,from,"hello");

            Client client   = new Client(serverAddress, portNumber,access);

            if(!client.start())
            return;

            while(true)
            {
                System.out.println("Please enter msg:");
                System.out.print("> ");
                // read message from user

                String msg = scan.nextLine();
                System.out.println("Sending message");

                    client.sendMessage(new RemoteAccess(to,from,msg));


            }


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

        }

        class ListenFromServer extends Thread {

            public void run() 
            {
                System.out.println("i am in run method");
                while(true) 
                {
                    System.out.println("i am in run method 2");
                    try 
                    {
                        System.out.println("i am in run method 3");
                        RemoteAccess access = (RemoteAccess) sInput.readObject();

                        System.out.println("Message read by:"+access.getFrom());
                        if(access !=null)
                        {
                            System.out.println("Message is :"+access.getFrom());
                        }




                    }
                    catch(IOException e)
                    {
                        e.printStackTrace();
                        System.out.println("Excepion caught while listening from server :"+e);
                        display(notif + "Server has closed the connection: " + e + notif);
                        break;
                    }
                    catch(ClassNotFoundException e2) {
                        e2.printStackTrace();
                    }
                }
            }
        }

        }


Server.java


    package customChat;

    import java.io.*;
    import java.net.*;
    import java.text.SimpleDateFormat;
    import java.util.*;



    public class Server {


        private SimpleDateFormat sdf;
        private int port;
        private boolean keepGoing;
        private String notif = " *** ";

        public static ArrayList<ClientThread> al;
        public Server(int port)
        {
            this.port = port;
            sdf = new SimpleDateFormat("HH:mm:ss");
            al = new ArrayList<ClientThread>();
        }

        public void start() {
            keepGoing = true;
            try 
            {
                ServerSocket serverSocket = new ServerSocket(port);

                while(keepGoing) 
                {
                    display("Server waiting for Clients on port " + port + ".");

                    Socket socket = serverSocket.accept();
                    if(!keepGoing)
                        break;
                    ClientThread t = new ClientThread(socket);
                    Thread t1 =new Thread(t);
                    System.out.println("Connection initiated by:"+t.access.getFrom());
                    Server.al.add(t);

                    t1.start();
                }
                /*try {
                    serverSocket.close();
                    for(int i = 0; i < Server.al.size(); ++i) {
                        ClientThread tc = Server.al.get(i);
                        try {
                        tc.sInput.close();
                        tc.sOutput.close();
                        tc.socket.close();
                        }
                        catch(IOException ioE) {
                            ioE.printStackTrace();
                        }
                    }
                }
                catch(Exception e) 
                {
                    display("Exception closing the server and clients: " + e);
                }*/
            }
            catch (IOException e) {
                String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
                display(msg);
            }
        }

        /*protected void stop() {
            keepGoing = false;
            try {
                new Socket("localhost", port);
            }
            catch(Exception e) {
            }
        }*/

        // Display an event to the console
        private void display(String msg) {
            String time = sdf.format(new Date()) + " " + msg;
            System.out.println(time);
        }






        public static void main(String[] args) {
            // start server on port 1500 unless a PortNumber is specified 
            int portNumber = 1502;

            // create a server object and start it
            Server server = new Server(portNumber);
            server.start();
        }

    }


    ClientThread.java


    package customChat;

    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.Date;

    /*class ListClient
    {

        public static  ArrayList<ClientThread> al=new ArrayList<>();;

    }*/
    public class ClientThread  implements Runnable {

        Socket                  socket;
        ObjectInputStream       sInput;     
        ObjectOutputStream      sOutput;    
        String                  date;
        RemoteAccess            access;

        public RemoteAccess getAccess() {
            return access;
        }

        public void setAccess(RemoteAccess access) {
            this.access = access;
        }

        // Constructor
        ClientThread(Socket socket) {

            this.socket = socket;

            System.out.println("Thread trying to create Object Input/Output Streams");
            try
            {
                sOutput = new ObjectOutputStream(socket.getOutputStream());
                sInput  = new ObjectInputStream(socket.getInputStream());
                System.out.println("CT input Stream :"+sInput);
                access = (RemoteAccess) sInput.readObject();

                System.out.println(access.getFrom() +"Joined the chat room");
            }
            catch (IOException e)
            {
                e.printStackTrace();
                System.out.println("Exception creating new Input/output Streams: " + e);
                return;
            }
            catch (ClassNotFoundException e)
            {
                e.printStackTrace();
            }
            date = new Date().toString() + "\n";
        }




        /*private void close() {
            try {
                if(sOutput != null) sOutput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            try {
                if(sInput != null) sInput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            };
            try {
                if(socket != null) socket.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    */
        @Override
        public void run() 
        {

            System.out.println("List size is :"+Server.al.size());

            for(int i=0;i<Server.al.size();i++)
            {
                try {
                    System.out.println("Socket input Stream :"+Server.al.get(i).socket.getInputStream());
                    System.out.println("Socket :"+socket.getInputStream());
                } catch (IOException e) {

                    e.printStackTrace();
                }
                if(Server.al.get(i).access.getFrom()==access.getTo())
                {
                    System.out.println("I am in if part :"+Server.al.get(i).access.getFrom() +"compare  to :"+access.getTo());
                    PairHandler t = null;
                    try {
                        t = new PairHandler(access.getTo(),Server.al.get(i).socket,Server.al.get(i).socket.getInputStream(),Server.al.get(i).socket.getOutputStream(),socket.getOutputStream(),socket.getInputStream(),socket);
                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                    Thread t1       =   new Thread(t);
                    System.out.println("Connection initiated by in CT:"+access.getFrom());

                    t1.start();
                }
                else{
                    System.out.println("I am in else in CT");

                }
            }
        }




    }

PairHandler.java

This is where i am using two client socket

    package customChat;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.net.Socket;



    public class PairHandler implements Runnable  
    {

        long                stbId;
        Socket              tvsocket;
        ObjectInputStream   tvsInput;
        ObjectOutputStream  tvsOutput;

        Socket              dtsocket;
        ObjectInputStream   dtsInput;
        ObjectOutputStream  dtsOutput;

        PairHandler(long stbId,Socket tvsocket,Socket dtsocket)
        {
            this.stbId      =   stbId;
            this.tvsocket   =   tvsocket;
            this.dtsocket   =   dtsocket;
            try
            {
                tvsOutput = new ObjectOutputStream(tvsocket.getOutputStream());
                dtsOutput = new ObjectOutputStream(dtsocket.getOutputStream());
                System.out.println("DT output Stream is :"+dtsOutput);
                System.out.println("Tv outPut Stream is :"+tvsOutput);


                System.out.println("RH input Stream :"+tvsocket.getInputStream());
                tvsInput  = new ObjectInputStream(tvsocket.getInputStream());
                System.out.println("Tv input Stream is :"+tvsInput);

                dtsInput  = new ObjectInputStream(dtsocket.getInputStream());
                System.out.println("DT input Stream is :"+dtsInput);
            }
            catch (IOException e)
            {
                e.printStackTrace();
                System.out.println("Exception creating in Pair Handler new Input/output Streams: " + e);
                return;
            }
        }


        public PairHandler(long to, Socket socket, InputStream inputStream, OutputStream outputStream,
                OutputStream outputStream2, InputStream inputStream2, Socket socket2) {


                stbId       =   to;
                tvsocket    =   socket;
                dtsocket    =   socket2;

                try{
                    tvsOutput = new ObjectOutputStream(outputStream);
                    dtsOutput = new ObjectOutputStream(outputStream2);
                    System.out.println("DT output Stream is :"+dtsOutput);
                    System.out.println("Tv input Stream is :"+socket.getInputStream());
                    System.out.println("DT input Stream is :"+socket2.getInputStream());



                    tvsInput  = new ObjectInputStream(socket2.getInputStream());
                    System.out.println("Tv input Stream is 2 :"+tvsInput);

                    dtsInput  = new ObjectInputStream(socket2.getInputStream());
                    System.out.println("DT input Stream is :"+dtsInput);
                    System.out.println("Tv input Stream is :"+tvsInput);

                // TODO Auto-generated constructor stub
                }
                catch (IOException e)
                {
                    System.out.println("Exception in PH");
                    e.printStackTrace();



                }
        }

        @Override
        public void run()
        {
            try
            {

                //dtsInput  = new ObjectInputStream(dtsocket.getInputStream());
                System.out.println("DT socket :"+dtsInput);
                if(dtsInput!=null){
                    RemoteAccess dtMsg = (RemoteAccess) dtsInput.readObject();

                    if(dtMsg !=null){

                        // write to tvscoket
                        System.out.println("I am here in Pair Handler");
                        sendTOTv(dtMsg);
                    }
                }


            //  tvsInput  = new ObjectInputStream(tvsocket.getInputStream());
                System.out.println("TV socket :"+tvsInput);
                if(tvsInput!=null){
                    RemoteAccess tvmsg = (RemoteAccess) tvsInput.readObject();
                    if(tvmsg !=null){

                        // write to dtsocket
                        sendToDT(tvmsg);
                    }
                }

            }
            catch (IOException e)
            {
                e.printStackTrace();
                System.out.println("Exception found while msg");


            }
            catch(ClassNotFoundException e2) {
                e2.printStackTrace();

            }


        }

        private void sendToDT(RemoteAccess tvmsg) {
            // TODO Auto-generated method stub


                // if Client is still connected send the message to it
                if(!dtsocket.isConnected()) 
                {
                    closeDtSocket();

                }
                try {

                    dtsOutput.writeObject(tvmsg);





                }
                catch(IOException e) {
                    System.out.println("Failed to deliver msg");

                }



        }
        private void closeDtSocket() {
            try {
                if(dtsOutput != null) dtsOutput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            try {
                if(dtsInput != null) dtsInput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            };
            try {
                if(dtsocket != null) dtsocket.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void closeTvSocket() {
            try {
                if(tvsOutput != null) tvsOutput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            try {
                if(tvsInput != null) tvsInput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            };
            try {
                if(tvsocket != null) tvsocket.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        private void sendTOTv(RemoteAccess dtMsg) {
            // TODO Auto-generated method stub
            if(!tvsocket.isConnected()) 
            {
                closeTvSocket();

            }
            try {

                tvsOutput.writeObject(dtMsg);





            }
            catch(IOException e) {
                System.out.println("Failed to deliver msg");

            }

        }


        }


RemoteAccess.java


package customChat;

import java.io.File;
import java.io.Serializable;

class RemoteAccess implements Serializable {


    private static final long serialVersionUID = 1L;

    private long to;
    private long from;
    private File file;
    private String msg;
    private int x ;
    private int y;



    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }



    RemoteAccess(){

    }
    RemoteAccess(long to,long from)
    {
        this.to=to;
        this.from=from;

    }

    RemoteAccess(long to,long from,File file)
    {
        this.to=to;
        this.from=from;
        this.file=file;

    }

    RemoteAccess(long to,long from,int x,int y)
    {
        this.to=to;
        this.from=from;
        this.x=x;
        this.y=y;

    }

    RemoteAccess(long to,long from,String msg)
    {
        this.to=to;
        this.from=from;
        this.msg=msg;

    }


    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public long getTo() {
        return to;
    }

    public void setTo(long to) {
        this.to = to;
    }

    public long getFrom() {
        return from;
    }

    public void setFrom(long from) {
        this.from = from;
    }



}

1 个答案:

答案 0 :(得分:0)

我想你想要自定义client1和client2。所以你应该为每一个创建一个类:

public class Client1 extends Socket {
    public Client1() {
        super();
    }
    //Add stuff to customize
}

public class Client2 extends Socket {
    public Client2() {
        super();
    }
    //Add stuff to customize
}

然后创建包含两个套接字的类:

public class ClientDialog {

     private Client1 client1;
     private Client2 client2;

     public ClientDialog() {
         client1 = new Client1();
         client2 = new Client1();
     }

     //Dialog between client

}