使用Java将客户端连接到多个服务器

时间:2013-03-30 18:13:55

标签: java sockets tcp

我希望客户端连接到多个服务器。即我希望我的客户向server1发送一个数字,该数字将数字平方并将其回送给客户端。但是,我希望客户端然后将此平方数发送到另一个端口上侦听的第二个服务器。

我不确定如何实现此功能,我可以通过线程执行此操作,还是只打开第二个套接字server2

这是我客户的代码。

import java.io.*;

import java.net.*;

public class ClientA {
    public static void main(String[] args) {

    String serverhost = "localhost";
    int serverport = 6789;

        Socket clientSocket = null;  
        DataOutputStream os = null;
        BufferedReader is = null;

   try {
            clientSocket = new Socket(serverhost, serverport);
            os = new DataOutputStream(clientSocket.getOutputStream());
            is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + serverhost);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: " + serverhost);
        } //end try

if (clientSocket == null || os == null || is == null) {
        System.err.println( "An error has occured, please restart." );
        return;
    } //end if

    try {
        while ( true ) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String keyboardInput = br.readLine();
        os.writeBytes( keyboardInput + "\n" );

        int n = Integer.parseInt( keyboardInput );
        if ( n == 0 ) {
            break;
        }

        String responseLine = is.readLine();
        System.out.println("Server returns its square as: " + responseLine);
        }

        os.close();
        is.close();
        clientSocket.close();   
    } catch (UnknownHostException e) {
        System.err.println("Trying to connect to unknown host: " + e);
    } catch (IOException e) {
        System.err.println("IOException:  " + e);
    } //end try
    } //end main
} //end class

1 个答案:

答案 0 :(得分:0)

根据您提供的信息,我认为不需要将其设置为多线程应用程序,因为当您收到来自第二台服务器的回复时,您只是向第二台服务器发送(即不接收)数据。第一台服务器只需将第二个套接字设置为另一个地址,并在从第一个服务器获取数据时发送数据。