简体   繁体   English

要测试服务器套接字连接,如何直接向其发送一个或多个字节?

[英]To test a server socket connection, how can I send a byte or bytes directly to it?

Let's say I have this example Java code running which listens on port 1234: 假设我正在运行以下示例Java代码,该示例在端口1234上进行侦听:

ServerSocket socket = new ServerSocket(1234);

And switches on the first byte received: 并打开收到的第一个字节:

Socket s = socket.accept();

byte[] buffer = new byte[1];
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
int read = bis.read(buffer, 0, 1);

switch (buffer[0]) {
case 0x01:
    System.out.println("One.");
    break;
case 0x02:
    System.out.println("Two.");
    break;
default:
    System.out.println("Other.");
    break;
}

Is there a way to test this code from an external source? 有没有办法从外部来源测试此代码? For example, could I use something like Telnet or NetCat to accomplish this? 例如,我可以使用Telnet或NetCat之类的工具来完成此操作吗?

You can do it with NetCat like this: 您可以使用NetCat做到这一点:

echo -e '\x02' | nc 127.0.0.1 1234

This will cause "Two." 这将导致“两个”。 to be output to the console of the Java application. 输出到Java应用程序的控制台。

You can do it with Telnet like this (Telnet will just send each key you type as an ASCII byte. If you want to send bytes less than the typeable characters, you can hold Ctrl down to subtract 64 from the ASCII value): 您可以使用Telnet这样进行操作(Telnet只会将您键入的每个键作为ASCII字节发送。如果要发送的字节数少于可键入的字符,则可以按住Ctrl并从ASCII值中减去64):

telnet 127.0.0.1 1234

Then press Ctrl+B to send 0x02 (B is ASCII value 66, so holding Ctrl subtracts 64 from the value). 然后按Ctrl+B发送0x02(B是ASCII值66,因此按住Ctrl可以从值中减去64)。 This will cause "Two." 这将导致“两个”。 to be output to the console of the Java application. 输出到Java应用程序的控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM