File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed
Chat example with socket lib Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ import socket
2
+
3
+
4
+ def Main ():
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
+ while message != '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 ()
Original file line number Diff line number Diff line change
1
+ import socket
2
+ import time
3
+
4
+
5
+ def Main ():
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
+ while True :
16
+ while True : # 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
+ except ConnectionResetError :
22
+ time .sleep (1 )
23
+ conn , addr = my_Socket .accept ()
24
+ print ("Connection from: " + str (addr ))
25
+ if data == "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 ()
You can’t perform that action at this time.
0 commit comments