[英]object sending through socket between actionscript server and java client
[英]Socket object is not same between server and client
有什么方法可以检查服务器端和客户端之间是否使用了相同的 Socket?
package net;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class DateServer {
public static final int LISTENING_PORT = 32007;
public static void main(String[] args) {
ServerSocket listener;
Socket connection;
try {
listener = new ServerSocket(LISTENING_PORT);
while (true) {
connection = listener.accept();
System.out.println(connection.hashCode());
sendDate(connection);
}
} catch (Exception e) {
return;
}
}
private static void sendDate(Socket client) {
try {
Date now = new Date();
PrintWriter outgoing = new PrintWriter(client.getOutputStream());
outgoing.println(now.toString());
outgoing.flush();
client.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
package net;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
public class DateClient {
public static final int LISTENING_PORT = 32007;
public static void main(String[] args) {
String hostName = "localhost";
Socket connection;
BufferedReader incoming;
try {
connection = new Socket(hostName, LISTENING_PORT);
System.out.println(connection.hashCode());
incoming = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lineFromServer = incoming.readLine();
System.out.println();
System.out.println(lineFromServer);
System.out.println();
incoming.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
服务器端的 Output。
1804094807
Output 在客户端。
1826771953
2021 年 3 月 7 日星期日 18:16:05 JST
hashCode 不同。 我以为是一样的
这个假设是错误的。 而且我不知道它来自哪里。 但是hashCode
只返回与本地object 关联的本地标识符。
正如 Steffen 所说,服务器端和客户端 sockets 的哈希码仅基于两个不同 JVM 中两个对象的 memory 地址。
equal
的是:
connection.getLocalSocketAddress()
connection.getRemoteSocketAddres()
反之亦然。 这包括hashCode()
和toString()
方法的结果,因为InetSockeAddress
覆盖了所有三个equals
、 hashCode
和toString
方法。
它取决于哈希码的实现,正如您在 Socket 的情况下看到的那样,哈希码对于在该进程中创建的实例是唯一的。
请看一下这个例子
Hashcode之所以相同,只是因为它是由Person的state驱动的,我们必须实现它。 然而,人对象的身份哈希码不同。
public static void main(String[] args) {
class Person {
private int age;
private int cash;
public Person(int age, int cash) {
this.age = age;
this.cash = cash;
}
@Override
public int hashCode() {
return (31 * age) + cash;
}
public int defaultHashCodeImplementation() {
return super.hashCode();
}
}
Person p1 = new Person(30, 100);
System.out.println("p1 hashcode: " + p1.hashCode());
System.out.println("p1 identity hashcode: " + p1.defaultHashCodeImplementation());
Person p2 = new Person(30, 100);
System.out.println("p2 hashcode: " + p2.hashCode());
System.out.println("p2 identity hashcode: " + p2.defaultHashCodeImplementation());
}
Output
p1 hashcode: 1030
p1 object identity hashcode: 1712669532
p2 hashcode: 1030
p2 object identity hashcode: 1225373914
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.