【发布时间】:2015-08-26 09:34:32
【问题描述】:
我一直在开发一个基本上类似于 Minechat 的 Java 程序(基于文本的应用程序来查看聊天。)我从来没有真正使用过网络太多,所以问题是弄清楚如何正确发送数据包。我目前正处于与服务器创建握手的位置。经过数小时的研究,我想出了以下代码,但它总是遇到“失败!(异常)”消息。对我来说,一切看起来都是正确的,但据我所知,这可能是 100% 错误的。如果有人能指出我在这里做错了什么,我将不胜感激。
public static void main(String[] args) throws IOException {
host = new InetSocketAddress("162.244.165.111", 48040);
socket = new Socket();
System.out.println("Connecting...");
socket.connect(host, 3000);
System.out.println("Done!");
System.out.println("Making streams...");
output = new DataOutputStream(socket.getOutputStream());
input = new DataInputStream(socket.getInputStream());
System.out.println("Done!");
System.out.println("Attempting handshake... "+host.getAddress().toString().substring(1));
byte[] msg = ("47;"+host.getAddress().toString().substring(1)+";"+host.getPort()+";2;").getBytes(Charset.forName("UTF-16"));
output.writeInt(msg.length+Integer.valueOf(0x00));
output.writeByte(0x00);
output.write(msg);
output.flush();
try {
if (input.readByte() != 0x02)
System.out.println("Failed!");
else
System.out.println("Done!");
} catch (EOFException e) {
System.out.println("Failed! (Exception)");
}
}
编辑: 更多研究表明我使用 Byte 数组,但这让我对如何表示字符串以及需要使用字符串感到困惑?
【问题讨论】:
标签: java network-programming minecraft packets