📜  插座 | Python

📅  最后修改于: 2022-05-13 01:55:30.497000             🧑  作者: Mango

插座 | Python

什么是插座?
套接字充当双向通信通道,它们是它的端点。套接字可以在进程内、不同进程之间以及不同位置的进程之间进行通信。
套接字模块- s.socket.socket(socket_family, socket_type, protocol=0)

一旦如上所述创建了套接字对象,现在我们可以使用下面的函数来创建客户端服务器程序。
套接字方法

Sr no.Method and Description

Server socket methods

1.

s.bind – This method binds address hostname, port number to socket

 
 

2.

s.listen – This method setups and start TCP listener

 
 

3.

s.accept – This passively accepts client connection, waiting until connection arrives blocking

 
 

Client socket methods

1.

s.connect – This method actively initiates TCP server connection

 
 

通用套接字方法

Sr no.Method and Description
1.

s.recv – This method receives TCP message

 
 

2.

s.send – This method transmits TCP message

 
 

3.

s.recvfrom – This method receives UDP message

 
 

4.

s.sendto – This method transmits UDP message

 
 

5.

s.close – This method closes socket

 
 

6.

s.gethostname – Returns a hostname

 
 

示例:从服务器向客户端发送日期

client side
Output :today's Date

Python3
# importing required modules
import socket    
import datetime
 
# initializing socket
s = socket.socket()    
host = socket.gethostname() 
port = 12345
 
# binding port and host
s.bind((host, port))  
 
# waiting for a client to connect
s.listen(5) 
        
while True:
   # accept connection
   c, addr = s.accept()       
   print ('got connection from addr', addr)
   date = datetime.datetime.now() 
   d = str(date)
 
   # sending data type should be string and encode before sending
   c.send(d.encode())     
   c.close()


Python3
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
 
# connect to host
s.connect((host, port))
 
# recv message and decode here 1024 is buffer size.   
print (s.recv(1024).decode())  
s.close()


Python3
import socket
 
localIP = "127.0.0.1"
localPort = 20001
bufferSize = 1024
 
UDPServerSocket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")
 
# this might be database or a file
di ={'17BIT0382':'vivek', '17BEC0647':'shikhar', '17BEC0150':'tanveer',
'17BCE2119':'sahil', '17BIT0123':'sidhant'}
 
while(True):
   # receiving name from client
   name, addr1 = UDPServerSocket.recvfrom(bufferSize) 
 
   # receiving pwd from client
   pwd, addr1 = UDPServerSocket.recvfrom(bufferSize) 
 
   name = name.decode() 
   pwd = pwd.decode()
   msg =''
   if name not in di:
       msg ='name does not exists'
       flag = 0
   for i in di:
      if i == name:
          if di[i]== pwd:
              msg ="pwd match"
              flag = 1
          else:
              msg ="pwd wrong"
      bytesToSend = str.encode(msg)
      # sending encoded status of name and pwd
      UDPServerSocket.sendto(bytesToSend, addr1)


Python3
import socket
 
# user input
name = input('enter your username : ')    
bytesToSend1 = str.encode(name)
password = input('enter your password : ')
bytesToSend2 = str.encode(password)
 
serverAddrPort = ("127.0.0.1", 20001)
bufferSize = 1024
 
# connecting to hosts
UDPClientSocket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM) 
 
# sending username by encoding it
UDPClientSocket.sendto(bytesToSend1, serverAddrPort) 
# sending password by encoding it
UDPClientSocket.sendto(bytesToSend2, serverAddrPort) 
 
# receiving status from server
msgFromServer = UDPClientSocket.recvfrom(bufferSize) 
msg = "Message from Server {}".format(msgFromServer[0].decode()) 
print(msg)


Python3

import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
 
# connect to host
s.connect((host, port))
 
# recv message and decode here 1024 is buffer size.   
print (s.recv(1024).decode())  
s.close()

注意:创建 2 个Python编译器实例分别运行客户端和服务器代码,不要在同一个实例上运行它们。
输出:
服务器端-

客户端-
此处显示从服务器获取的当前日期时间

UDP 套接字

UDP 是 USER DATAGRAM PROTOCOL ,这是一个轻量级协议,它具有基本的错误检查机制,没有确认和排序,但由于这些原因非常快
示例:从服务器向客户端发送日期

client side
Input : vivek  
Input : 17BIT0382  
Output : password match 

Python3

import socket
 
localIP = "127.0.0.1"
localPort = 20001
bufferSize = 1024
 
UDPServerSocket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")
 
# this might be database or a file
di ={'17BIT0382':'vivek', '17BEC0647':'shikhar', '17BEC0150':'tanveer',
'17BCE2119':'sahil', '17BIT0123':'sidhant'}
 
while(True):
   # receiving name from client
   name, addr1 = UDPServerSocket.recvfrom(bufferSize) 
 
   # receiving pwd from client
   pwd, addr1 = UDPServerSocket.recvfrom(bufferSize) 
 
   name = name.decode() 
   pwd = pwd.decode()
   msg =''
   if name not in di:
       msg ='name does not exists'
       flag = 0
   for i in di:
      if i == name:
          if di[i]== pwd:
              msg ="pwd match"
              flag = 1
          else:
              msg ="pwd wrong"
      bytesToSend = str.encode(msg)
      # sending encoded status of name and pwd
      UDPServerSocket.sendto(bytesToSend, addr1) 

Python3

import socket
 
# user input
name = input('enter your username : ')    
bytesToSend1 = str.encode(name)
password = input('enter your password : ')
bytesToSend2 = str.encode(password)
 
serverAddrPort = ("127.0.0.1", 20001)
bufferSize = 1024
 
# connecting to hosts
UDPClientSocket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM) 
 
# sending username by encoding it
UDPClientSocket.sendto(bytesToSend1, serverAddrPort) 
# sending password by encoding it
UDPClientSocket.sendto(bytesToSend2, serverAddrPort) 
 
# receiving status from server
msgFromServer = UDPClientSocket.recvfrom(bufferSize) 
msg = "Message from Server {}".format(msgFromServer[0].decode()) 
print(msg)

为简化代码,我选择了一个字典,您可以将数据库、文件或 CSV 文件等用于各种其他目的。
输出: