小编Par*_*los的帖子

我需要服务器向所有客户端发送消息(Python,套接字)

这是我的服务器程序,它如何将从每个客户端收到的数据发送给每个其他客户端?

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)

python sockets networking multithreading tcp

5
推荐指数
1
解决办法
1万
查看次数

为什么最后一个对象在ArrayList中被多次复制?

我正在尝试将名为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)

java arraylist

4
推荐指数
2
解决办法
174
查看次数

标签 统计

arraylist ×1

java ×1

multithreading ×1

networking ×1

python ×1

sockets ×1

tcp ×1