Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit6186d7d

Browse files
committed
Chat example with socket lib
1 parent74cd41c commit6186d7d

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
importsocket
2+
3+
4+
defMain():
5+
host='localhost'
6+
port=1234
7+
8+
my_Socket=socket.socket()
9+
my_Socket.connect((host,port))
10+
11+
print("Connected! {}:{}".format(host,port))
12+
13+
message=input(" -> ")
14+
print("Waiting Server...")
15+
16+
whilemessage!='q':
17+
my_Socket.send(message.encode())
18+
data=my_Socket.recv(1024).decode()
19+
20+
print('Server: '+data)
21+
22+
message=input(" -> ")
23+
print("Waiting Server...")
24+
25+
my_Socket.close()
26+
27+
28+
if__name__=='__main__':
29+
Main()
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
importsocket
2+
importtime
3+
4+
5+
defMain():
6+
host="localhost"
7+
port=1234
8+
9+
my_Socket=socket.socket()
10+
my_Socket.bind((host,port))
11+
12+
my_Socket.listen(1)
13+
conn,addr=my_Socket.accept()
14+
print("Connection from: "+str(addr))
15+
whileTrue:
16+
whileTrue:# this line, if the client closed the connection, it waits for new connections.
17+
try:
18+
data=str(conn.recv(1024).decode())
19+
print("Client: "+data)
20+
break
21+
exceptConnectionResetError:
22+
time.sleep(1)
23+
conn,addr=my_Socket.accept()
24+
print("Connection from: "+str(addr))
25+
ifdata=="q":
26+
break
27+
else:
28+
message=input(" -> ")
29+
print("Waiting Client...")
30+
conn.send(message.encode())
31+
conn.close()
32+
33+
34+
if__name__=='__main__':
35+
Main()

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp