【发布时间】:2012-06-23 20:00:00
【问题描述】:
我正在尝试为充当 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;
}
}
问题是VB1程序不接受我程序的输入。
我将成功设备的网络数据包捕获与我自己程序的流量捕获进行了比较,所有相关的内容都是相同的...除了回复端口。
在我的程序中,serversocket 随机分配一个端口来响应 VB6 程序,但是当 VB6 程序连接到我试图模拟的物理设备时,设备只回复端口 1602。
我的问题是,当我正在监听端口 23 进行连接时(这很好),我如何获得创建的套接字以在端口 1602 上进行回复,而不是在 2000 - 3000 标记附近随机跳转?
我能看到的所有回复和问题都围绕着套接字或多线程,而没有锁定等待连接的端口。
如果这不是一个观众,那么有人可以指出我想要实现的 UI 的更好解决方案吗?
我知道有人会说为什么不用实际设备设置一个装备,但它们很贵而且我没有现成的备用设备来安装钻机。那个,现在这个问题已经向我提出,我不禁要找出发生了什么! :-)
【问题讨论】:
标签: java tcp port serversocket