这是我的服务器程序,它如何将从每个客户端收到的数据发送给每个其他客户端?
import socket
import os
from threading import Thread
import thread
def listener(client, address):
print "Accepted connection from: ", address
while True:
data = client.recv(1024)
if not data:
break
else:
print repr(data)
client.send(data)
client.close()
host = socket.gethostname()
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
while True:
print "Server is listening for connections..."
client, address = s.accept()
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
Run Code Online (Sandbox Code Playgroud) 我正在尝试将名为City的类的对象添加到.这是该类的代码ArrayList
public class City {
public static int x;
public static int y;
City(){
Random rand = new Random();
this.x = rand.nextInt(100)+1;
this.y = rand.nextInt(100)+1;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的Main类的代码
public static int N = 10;
public static ArrayList<City> cities = new ArrayList<City>();
public static void main(String[] args) {
for (int i=1; i<N; i++){
cities.add(new City());
}
for (City c : cities)
System.out.print("("+c.x+", "+c.y+")");
}
}
Run Code Online (Sandbox Code Playgroud)
结果println总是相同的,似乎数组列表只存储其所有元素中添加的最后一个对象.
例如,我运行程序时得到的结果是:
(52, 93)(52, 93)(52, …Run Code Online (Sandbox Code Playgroud)