如何在java中进行多个套接字通信?

发布于 2024-10-10 03:15:51 字数 6163 浏览 0 评论 0原文

我有许多套接字连接到具有不同 IP 地址和不同端口号的不同系统。我的问题是我必须在任何系统中运行一个程序才能一次与所有套接字进行通信,以及如何并行从套接字获取消息?

当我使用单套接字时,它会正常工作,并且我不断从超级终端获取消息。多个连接,然后我只收到第一个的响应..所以请尽快提供解决方案


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import com.ibatis.sqlmap.client.SqlMapClient;

public class Client1 extends Thread {
    static Socket socket;
    static Socket socket1;
    static String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
    static SqlMapClient sqlMap=GetDBConnection.sqlMap;
    static BufferedReader br = null;
    static DataOutputStream dos=null;
    static BufferedReader br1 = null;
    static DataOutputStream dos1=null;
    public static void main(String args[]){
        try{
            String host="192.168.1.151";
            int port=5002;
            String host1="192.168.1.150";
            int port1=5001;
            socket = new Socket(host, port);
            socket1=new Socket(host1, port1);
            dos = new DataOutputStream(socket.getOutputStream());
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            dos1 = new DataOutputStream(socket1.getOutputStream());
            br1 = new BufferedReader(new InputStreamReader(socket1.getInputStream()));

            Thread t = new Thread(new Runnable() {
            public void run() {
                while(socket.isConnected()) {
                    try{
                        HashMap map = new HashMap();
                        String str = br.readLine();
                        Calendar cal = Calendar.getInstance();
                        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                        String time = sdf.format(cal.getTime());
                        map.put("data", str);
                        map.put("port", socket.getPort());
                        map.put("date_time", time);
                        sqlMap.insert("insert", map);
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }
                }
               }
            });

            Thread t1 = new Thread(new Runnable() {
            public void run() {
                while(socket1.isConnected()) {
                    try{
                        HashMap map = new HashMap();
                        String str = br1.readLine();
                        Calendar cal = Calendar.getInstance();
                        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                        String time = sdf.format(cal.getTime());
                        map.put("data", str);
                        map.put("port", socket1.getPort());
                        map.put("date_time", time);
                        sqlMap.insert("insert", map);
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }
                  }
                }
            });

            t.start();
            t1.start();
            }
            catch(Exception e){
                e.printStackTrace();
            }
    }
}

我正在为两个套接字运行两个线程,它工作正常,但如果我有 100 个套接字,那么我该怎么做?我无法创建 100 个线程...因此请提供最佳解决方案...


public class Client implements Runnable{

    public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
        static BufferedReader br = null;
        static DataOutputStream dos=null;
        static Socket socket = null;
        SqlMapClient sqlMap=GetDBConnection.sqlMap;

        Client(String host, int port)
        {
            try {

                socket = new Socket(host, port);
            } catch (UnknownHostException e) {
                        e.printStackTrace();
            } catch (IOException e) {
                        e.printStackTrace();
            } 
        }

    public void run()
    {
        try {

            HashMap map = new HashMap(5); 
            String str;
            int prt=socket.getPort();
            dos = new DataOutputStream(socket.getOutputStream());
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while((str=br.readLine())!=null)
            {
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                String time = sdf.format(cal.getTime());
                map.put("data", str);

                map.put("port",prt );
                map.put("date_time", time);
                sqlMap.insert("insert", map);
             }
        }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            finally 
            {
                try {

                    socket.close();
                    dos.close();
                    br.close();
                } catch (IOException e) {
                        e.printStackTrace();
                }
            }
    }

    public static void main(String args[]) 
    {
        ResultSet rs=null; 
        Connection con = null;

      try {
            Class.forName("org.postgresql.Driver");
            con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Socket","username","passwd");
            Statement st=con.createStatement(); 
            String vsql="select port, ip_addr from port_instrument";
            rs=st.executeQuery(vsql);
               while (rs.next()) {
                 String id = rs.getString(1);

                 String ipaddr = rs.getString(2);

                 new Thread(new Client(ipaddr, Integer.parseInt(id))).start();

               }
       }
       catch(Exception e)
       {
         e.printStackTrace();
       }
       finally{
           try {
                con.close();
                rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
       }
    }
}

通过使用此代码,我们只能与单个套接字进行通信。在我的数据库中,我有 5 个套接字,但最终我仅从最后一个套接字(5)进行通信。

I have number of sockets connected to different systems with different ip-address with different port numbers. my question is I have to run one program in any system to communicate all the sockets at a time and how can i get the messages from sockets in parallel?

While I am using single socket it will work fine and I am getting messages continuously from hyper terminal. more than one connected ,then I am getting response from first one only.. so please provide the solution asap


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import com.ibatis.sqlmap.client.SqlMapClient;

public class Client1 extends Thread {
    static Socket socket;
    static Socket socket1;
    static String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
    static SqlMapClient sqlMap=GetDBConnection.sqlMap;
    static BufferedReader br = null;
    static DataOutputStream dos=null;
    static BufferedReader br1 = null;
    static DataOutputStream dos1=null;
    public static void main(String args[]){
        try{
            String host="192.168.1.151";
            int port=5002;
            String host1="192.168.1.150";
            int port1=5001;
            socket = new Socket(host, port);
            socket1=new Socket(host1, port1);
            dos = new DataOutputStream(socket.getOutputStream());
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            dos1 = new DataOutputStream(socket1.getOutputStream());
            br1 = new BufferedReader(new InputStreamReader(socket1.getInputStream()));

            Thread t = new Thread(new Runnable() {
            public void run() {
                while(socket.isConnected()) {
                    try{
                        HashMap map = new HashMap();
                        String str = br.readLine();
                        Calendar cal = Calendar.getInstance();
                        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                        String time = sdf.format(cal.getTime());
                        map.put("data", str);
                        map.put("port", socket.getPort());
                        map.put("date_time", time);
                        sqlMap.insert("insert", map);
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }
                }
               }
            });

            Thread t1 = new Thread(new Runnable() {
            public void run() {
                while(socket1.isConnected()) {
                    try{
                        HashMap map = new HashMap();
                        String str = br1.readLine();
                        Calendar cal = Calendar.getInstance();
                        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                        String time = sdf.format(cal.getTime());
                        map.put("data", str);
                        map.put("port", socket1.getPort());
                        map.put("date_time", time);
                        sqlMap.insert("insert", map);
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }
                  }
                }
            });

            t.start();
            t1.start();
            }
            catch(Exception e){
                e.printStackTrace();
            }
    }
}

I am running two threads for two sockets its work fine, but if I have 100 sockets then how can I do it? I can't create 100's of threads...so provide the best solution..


public class Client implements Runnable{

    public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
        static BufferedReader br = null;
        static DataOutputStream dos=null;
        static Socket socket = null;
        SqlMapClient sqlMap=GetDBConnection.sqlMap;

        Client(String host, int port)
        {
            try {

                socket = new Socket(host, port);
            } catch (UnknownHostException e) {
                        e.printStackTrace();
            } catch (IOException e) {
                        e.printStackTrace();
            } 
        }

    public void run()
    {
        try {

            HashMap map = new HashMap(5); 
            String str;
            int prt=socket.getPort();
            dos = new DataOutputStream(socket.getOutputStream());
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while((str=br.readLine())!=null)
            {
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
                String time = sdf.format(cal.getTime());
                map.put("data", str);

                map.put("port",prt );
                map.put("date_time", time);
                sqlMap.insert("insert", map);
             }
        }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            finally 
            {
                try {

                    socket.close();
                    dos.close();
                    br.close();
                } catch (IOException e) {
                        e.printStackTrace();
                }
            }
    }

    public static void main(String args[]) 
    {
        ResultSet rs=null; 
        Connection con = null;

      try {
            Class.forName("org.postgresql.Driver");
            con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Socket","username","passwd");
            Statement st=con.createStatement(); 
            String vsql="select port, ip_addr from port_instrument";
            rs=st.executeQuery(vsql);
               while (rs.next()) {
                 String id = rs.getString(1);

                 String ipaddr = rs.getString(2);

                 new Thread(new Client(ipaddr, Integer.parseInt(id))).start();

               }
       }
       catch(Exception e)
       {
         e.printStackTrace();
       }
       finally{
           try {
                con.close();
                rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
       }
    }
}

By using this code we can communicate with the single socket only. In my database I have 5 sockets but finally I get communication from last socket(5) only.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笑脸一如从前 2024-10-17 03:15:51

您可能想要编写一个实现 Runnable 并执行所有套接字通信的通信类。然后,您可以为每个套接字创建此类的实例,并在某种线程池中运行这些类。

编辑:这是你的开始

public class SocketHandler implements Runnable
{
  private Socket socket;

  public SocketHandler(String host, int port)
  {
    socket = new Socket(host, port);
  }

  public void run()
  {
    //Do the comms to the remote server
  }
}

You might want to write a communication class that implements Runnable and does all the socket comms. You could then create an instance of this class for each socket and run the classes in some sort of thread pool.

Edit: Here's a start for you

public class SocketHandler implements Runnable
{
  private Socket socket;

  public SocketHandler(String host, int port)
  {
    socket = new Socket(host, port);
  }

  public void run()
  {
    //Do the comms to the remote server
  }
}
泪痕残 2024-10-17 03:15:51

您需要在不同的线程中从每个套接字读取数据,否则您的应用程序将阻止侦听其中一个套接字,即使其他套接字上有数据需要读取。因此,如果您有 x 个套接字,则必须创建 x 个从中读取数据的线程。

You need to read from each socket in a different thread, otherwise your application will block listening on one of the sockets, even if there is data to be read on the others. So if you have x sockets you have to create x threads that read from them.

谈场末日恋爱 2024-10-17 03:15:51

Jboss Netty 是一个不错的选择。

Jboss Netty is quite good choice to do it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文