Vì vậy, tôi đang làm việc trên một ứng dụng iPhone yêu cầu ổ cắm để xử lý nhiều máy khách để chơi game trực tuyến. Tôi đã thử xoắn, và với nhiều nỗ lực, tôi đã không nhận được một loạt các thông tin được gửi cùng một lúc, đó là lý do tại sao bây giờ tôi sẽ thử ổ cắm.
Câu hỏi của tôi là, sử dụng mã bên dưới, làm thế nào bạn có thể kết nối nhiều máy khách? Tôi đã thử danh sách, nhưng tôi không thể tìm ra định dạng cho điều đó. Làm thế nào điều này có thể được thực hiện khi nhiều máy khách được kết nối cùng một lúc và tôi có thể gửi tin nhắn cho một khách hàng cụ thể?
Cảm ơn bạn!
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket[] # Create a socket object
host = socket.gethostname[] # Get local machine name
port = 50000 # Reserve a port for your service.
print 'Server started!'
print 'Waiting for clients...'
s.bind[[host, port]] # Bind to the port
s.listen[5] # Now wait for client connection.
c, addr = s.accept[] # Establish connection with client.
print 'Got connection from', addr
while True:
msg = c.recv[1024]
print addr, ' >> ', msg
msg = raw_input['SERVER >> ']
c.send[msg];
#c.close[] # Close the connection
Khi được hỏi ngày 30 tháng 5 năm 2012 lúc 5:01May 30, 2012 at 5:01
12
Dựa trên câu hỏi của bạn:
Câu hỏi của tôi là, sử dụng mã bên dưới, làm thế nào bạn có thể kết nối nhiều máy khách? Tôi đã thử danh sách, nhưng tôi không thể tìm ra định dạng cho điều đó. Làm thế nào điều này có thể được thực hiện khi nhiều máy khách được kết nối cùng một lúc và tôi có thể gửi tin nhắn cho một khách hàng cụ thể?
Cảm ơn bạn!
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import thread
def on_new_client[clientsocket,addr]:
while True:
msg = clientsocket.recv[1024]
#do some checks and if msg == someWeirdSignal: break:
print addr, ' >> ', msg
msg = raw_input['SERVER >> ']
#Maybe some code to compute the last digit of PI, play game or anything else can go here and when you are done.
clientsocket.send[msg]
clientsocket.close[]
s = socket.socket[] # Create a socket object
host = socket.gethostname[] # Get local machine name
port = 50000 # Reserve a port for your service.
print 'Server started!'
print 'Waiting for clients...'
s.bind[[host, port]] # Bind to the port
s.listen[5] # Now wait for client connection.
print 'Got connection from', addr
while True:
c, addr = s.accept[] # Establish connection with client.
thread.start_new_thread[on_new_client,[c,addr]]
#Note it's [addr,] not [addr] because second parameter is a tuple
#Edit: [c,addr]
#that's how you pass arguments to functions when creating new threads using thread module.
s.close[]
Khi được hỏi ngày 30 tháng 5 năm 2012 lúc 5:01
Dựa trên câu hỏi của bạn:
Sử dụng mã bạn đã đưa ra, bạn có thể làm điều này:7 gold badges26 silver badges35 bronze badges
Như Eli Bendersky đã đề cập, bạn có thể sử dụng các quy trình thay vì các luồng, bạn cũng có thể kiểm tra mô -đun Python threading
hoặc khung ổ cắm Async khác. Lưu ý: Kiểm tra được để lại để bạn thực hiện theo cách bạn muốn và đây chỉ là một khung cơ bản.Oct 31, 2016 at 21:40
RKTAjcchuks
3.5367 Huy hiệu vàng26 Huy hiệu bạc35 Huy hiệu Đồng8 silver badges16 bronze badges
4
Đã trả lời ngày 31 tháng 10 năm 2016 lúc 21:40
- jcchuksjcchuks
- 8438 Huy hiệu bạc16 Huy hiệu đồng
accept
có thể liên tục cung cấp các kết nối khách hàng mới. Tuy nhiên, lưu ý rằng nó và các cuộc gọi ổ cắm khác thường bị chặn. Do đó, bạn có một vài tùy chọn tại thời điểm này:
Mở các chủ đề mới để xử lý khách hàng, trong khi chủ đề chính quay lại chấp nhận khách hàng mớiMay 30, 2012 at 6:04
Như trên nhưng với các quy trình, thay vì chủ đềEli Bendersky
Sử dụng các khung ổ cắm không đồng bộ như xoắn, hoặc rất nhiều người khác87 gold badges344 silver badges406 bronze badges
1
Đã trả lời ngày 30 tháng 5 năm 2012 lúc 6:04
import SocketServer
class MyTCPHandler[SocketServer.BaseRequestHandler]:
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle[] method to implement communication to the
client.
"""
def handle[self]:
# self.request is the TCP socket connected to the client
self.data = self.request.recv[1024].strip[]
print "{} wrote:".format[self.client_address[0]]
print self.data
# just send back the same data, but upper-cased
self.request.sendall[self.data.upper[]]
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer[[HOST, PORT], MyTCPHandler]
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever[]
Eli Benderskyeli Bendersky
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
HELLOConnection closed by foreign host.
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Sausage
SAUSAGEConnection closed by foreign host.
254K87 Huy hiệu vàng344 Huy hiệu bạc406 Huy hiệu đồng
Dưới đây là ví dụ từ tài liệu Socketserver sẽ tạo ra một điểm khởi đầu tuyệt vờiMay 30, 2012 at 6:05
Hãy thử nó từ một thiết bị đầu cuối như thế nàyNick Craig-Wood
Có lẽ bạn cũng cần phải sử dụng mixin hoặc xâu chuỗi12 gold badges123 silver badges130 bronze badges
3
Đã trả lời ngày 30 tháng 5 năm 2012 lúc 6:05
#!usr/bin/python
from thread import *
import socket
import sys
def clientthread[conn]:
buffer=""
while True:
data = conn.recv[8192]
buffer+=data
print buffer
#conn.sendall[reply]
conn.close[]
def main[]:
try:
host = '192.168.1.3'
port = 6666
tot_socket = 26
list_sock = []
for i in range[tot_socket]:
s = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
s.setsockopt[socket.SOL_SOCKET,socket.SO_REUSEADDR,1]
s.bind[[host, port+i]]
s.listen[10]
list_sock.append[s]
print "[*] Server listening on %s %d" %[host, [port+i]]
while 1:
for j in range[len[list_sock]]:
conn, addr = list_sock[j].accept[]
print '[*] Connected with ' + addr[0] + ':' + str[addr[1]]
start_new_thread[clientthread ,[conn,]]
s.close[]
except KeyboardInterrupt as msg:
sys.exit[0]
if __name__ == "__main__":
main[]
Nick Craig-Woodnick Craig-WoodApr 20, 2017 at 17:28
0
def get_clients[]:
first_run = True
startMainMenu = False
while True:
if first_run:
global done
done = False
Thread[target=animate, args=["Waiting For Connection",]].start[]
Client, address = objSocket.accept[]
global menuIsOn
if menuIsOn:
menuIsOn = False # will stop main menu
startMainMenu = True
done = True
# Get Current Directory in Client Machine
current_client_directory = Client.recv[1024].decode["utf-8", errors="ignore"]
# beep on connection
beep[]
print[f"{bcolors.OKBLUE}\n***** Incoming Connection *****{bcolors.OKGREEN}"]
print['* Connected to: ' + address[0] + ':' + str[address[1]]]
try:
get_client_info[Client, first_run]
except Exception as e:
print["Error data received is not a json!"]
print[e]
now = datetime.now[]
current_time = now.strftime["%D %H:%M:%S"]
print["* Current Time =", current_time]
print["* Current Folder in Client: " + current_client_directory + bcolors.WARNING]
connections.append[Client]
addresses.append[address]
if first_run:
Thread[target=threaded_main_menu, daemon=True].start[]
first_run = False
else:
print[f"{bcolors.OKBLUE}* Hit Enter To Continue.{bcolors.WARNING}\n#>", end=""]
if startMainMenu == True:
Thread[target=threaded_main_menu, daemon=True].start[]
startMainMenu = False
51.8K12 Huy hiệu vàng123 Huy hiệu bạc130 Huy hiệu đồngJan 30, 2021 at 14:20
1
Chương trình này sẽ mở 26 ổ cắm nơi bạn có thể kết nối rất nhiều máy khách TCP với nó.
Đã trả lời ngày 20 tháng 4 năm 2017 lúc 17:28Aug 17, 2021 at 15:11
#!/usr/bin/python
import sys
import os
import socket
s = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
port = 50000
try:
s.bind[[socket.gethostname[] , port]]
except socket.error as msg:
print[str[msg]]
s.listen[10]
conn, addr = s.accept[]
print 'Got connection from'+addr[0]+':'+str[addr[1]]]
while 1:
msg = s.recv[1024]
print +addr[0]+, ' >> ', msg
msg = raw_input['SERVER >>'],host
s.send[msg]
s.close[]
Đã trả lời ngày 30 tháng 1 năm 2021 lúc 14:20Oct 27, 2017 at 16:56
Bạn có thể sử dụng Pysock, một thư viện Python giúp việc viết các máy chủ đa máy tính cực kỳ dễ dàng. Bạn có thể tải xuống từ PYPI, cho Windows: pip install PySock
và cho Linux:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import thread
def on_new_client[clientsocket,addr]:
while True:
msg = clientsocket.recv[1024]
#do some checks and if msg == someWeirdSignal: break:
print addr, ' >> ', msg
msg = raw_input['SERVER >> ']
#Maybe some code to compute the last digit of PI, play game or anything else can go here and when you are done.
clientsocket.send[msg]
clientsocket.close[]
s = socket.socket[] # Create a socket object
host = socket.gethostname[] # Get local machine name
port = 50000 # Reserve a port for your service.
print 'Server started!'
print 'Waiting for clients...'
s.bind[[host, port]] # Bind to the port
s.listen[5] # Now wait for client connection.
print 'Got connection from', addr
while True:
c, addr = s.accept[] # Establish connection with client.
thread.start_new_thread[on_new_client,[c,addr]]
#Note it's [addr,] not [addr] because second parameter is a tuple
#Edit: [c,addr]
#that's how you pass arguments to functions when creating new threads using thread module.
s.close[]
0. Họ có mã tấm nồi hơi rất tốt trên trang giới thiệu PYPI. Bạn có thể kiểm tra nó ở đây hoặc truy cập github repo để biết thêm thông tin chi tiết về các phiên bản. Có một số tính năng tuyệt vời mà nó cung cấp là giao tiếp khách hàng-khách hàng mà không cần thêm bất kỳ nỗ lực nào, bạn có thể thực hiện các giao tiếp này được mã hóa E2E.Skiller DzĐã trả lời ngày 17 tháng 8 năm 2021 lúc 15:1110 silver badges17 bronze badges