如何在JAVA中更改serversocket连接的回复端口

时间:2012-06-21 14:42:08

标签: java tcp port serversocket


我正在尝试为充当TCP / IP服务器的硬连线设备编写模拟器 我有一个VB6程序,它连接到这个服务器并进行通信然而这是间歇性失败的,我需要确定出了什么问题所以我正在编写一个程序来模拟服务器。
我已经构建了以下Java程序来监听来自VB程序的连接,并使用与服务器设备相同的信息进行响应。

public class ServerSim {

public static void main(String[] args){
    int port = 23;
    System.out.println("[Listening for Connection]");
    try{
        ServerSocket ss;
        ss = new ServerSocket(port);
        Socket s;

        // The program will wait here until a connection is made.
        s = ss.accept();

        // Print what client we're connected to.
        String client;
        client = s.getInetAddress().toString();
        String localPort = Integer.toString(s.getLocalPort());
        String portNo = Integer.toString(s.getPort());

        System.out.println("[Connected to "+client +"] Port:" + portNo + " localPort: " + localPort);

        //Set up Scanner / Writer to read / write data to client.
        Scanner in;
        //Scanner sc = new Scanner(System.in);

        in = new Scanner(s.getInputStream());
        PrintWriter out;
        out = new PrintWriter(s.getOutputStream(),true);

        PrintWriter log = openWriter("Log.txt");

        // Establish a 5second connection
        s.setSoTimeout(5000);

        try{
            boolean result = establishConnection(in, out);
            String input = in.nextLine();
            System.out.println("Recieved: " + input);
            String response = input;
            out.println(response);
            System.out.println("Responded: " + response);
            log.println(input + "->" + response);
       }
       catch(Exception e){
           System.err.println("EXC: "+e.getMessage());                   
           e.printStackTrace();                   
       }
       System.out.println("[Closing Connections]");
       in.close();
        out.close();
        log.close();
        s.close();
        ss.close();

    }catch(Exception e){
        e.printStackTrace();            
    }        
}
    private static boolean establishConnection(Scanner in, PrintWriter out){
        // we have a connnection - Start by outputtinga  welcome message.       
        out.print("Welcome Session 0\r\n");
        out.flush();            
        out.print("User:\r\n");
        out.flush();
        System.out.println("[Welcome sent - Waiting Response]");
        String input = in.nextLine(); // Recieve the first line.  Should be a User
        System.out.println("[Recieved '"+input+"' - Sending anticipated reply]");
        out.println("Password:");
        input = in.nextLine(); // Recieve the first line.  Should be a User
        System.out.println("[Recieved '"+input+"' - Sending anticipated reply]");
        out.println("User Logged in");      
        return true;
    }
   private static PrintWriter openWriter(String name){
        try{
            File file = new File(name);
            PrintWriter out = new PrintWriter(
                    new BufferedWriter(
                    new FileWriter(file, true)),true);
            return out;
        }
        catch(IOException e){
            System.out.println("I/O Error");
            System.exit(0);
        }
        return null;
    }

}

问题是VB 1 程序不接受我程序的输入。

我将成功设备的网络数据包捕获与我自己程序的流量捕获进行了比较,相关的一切都是相同的...... 除了以外的回复端口。
在我的程序中,serversocket随机分配一个端口用于响应VB6程序,但是当VB6程序连接到我试图模拟的物理设备时,设备只回复端口1602。

我的问题是当我正在侦听端口23进行连接时(这种情况正常),如何获得创建的套接字以在端口1602上回复而不是随机跳转到2000-3000标记?

我能看到的所有回复和问题都是套接字或多线程,而没有锁定端口等待连接。
如果这不是一个观众,那么有人能指出我想要实现UI的更好的解决方案吗? 我知道有人会说为什么不用实际设备设置装备,但是它们很昂贵,而且我没有准备好使用备用装备进行装配。那现在问题已经提出来了,我不禁要知道发生了什么! :-)

1 编辑:我无法询问VB程序,因为它使用一系列ActiveX与设备通信并处理协议。这是我试图找到的问题可能来源,所以我不想写出来。

3 个答案:

答案 0 :(得分:0)

如果你想回复端口1602上的vb-app(并且vb-app还没有使用端口1602),你需要另一个(新的)套接字。

ServerSocket.accept();

返回java.net.Socket。此连接由4个属性标识:client-port,client-ip,server-port,server-ip。

这不是服务器(您的程序),它随机分配(您所谓的)回复端口,它是客户端(vb-app)。如果客户端不这样做,服务器将不知道应该在何处传递响应数据包。

您可能想要使用vb应用程序的ip和端口1602创建java.net.Socket。很有可能vb-app充当客户端服务器。

答案 1 :(得分:0)

尝试java.net.Socket ..我给你的​​代码片段,我用来模拟在指定端口运行的服务器。我希望这将是你的使用....

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

public class ServerTest {

    ServerSocket s;

    public void go() {

        try {
            s = new ServerSocket(44457);

            while (true) {

                Socket incoming = s.accept();
                Thread t = new Thread(new MyCon(incoming));
                t.start();
            }
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

    class MyCon implements Runnable {

        Socket incoming;

        public MyCon(Socket incoming) {

            this.incoming = incoming;
        }

        @Override
        public void run() {

            try {
                PrintWriter pw = new PrintWriter(incoming.getOutputStream(),
                        true);
                InputStreamReader isr = new InputStreamReader(
                        incoming.getInputStream());
                BufferedReader br = new BufferedReader(isr);
                String inp = null;

                boolean isDone = true;

                System.out.println("TYPE : BYE");
                System.out.println();
                while (isDone && ((inp = br.readLine()) != null)) {

                    System.out.println(inp);
                    if (inp.trim().equals("BYE")) {
                        System.out
                                .println("THANKS FOR CONNECTING...Bye for now");
                        isDone = false;
                        s.close();
                    }

                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                try {
                    s.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }

        }

    }

    public static void main(String[] args) {

        new ServerTest().go();

    }

}

答案 2 :(得分:0)

  

“serversocket随机为响应分配一个端口”。

我不明白这个说法。 Socket接受的ServerSocket具有本地端口号23(ServerSocket正在侦听的端口号),以及客户端连接时确定的远程端口号。这不受服务器程序的控制。设备可能只使用端口1602作为其输出端口,但VB程序几乎肯定会让操作系统决定端口号。

我认为你需要根据这些信息重新分析你的观察结果。

相关问题