这是一篇介绍Socket编程的文章,简单的附上代码

Socket是网络通信的基础,是进程通讯的一种方式,通过这个网络库的一些API可以实现分部在不同主机上的相关进程之间的数据交换

1)IP地址: 即按照TCP/IP协议分配给本地主机的网络地址,两个进程要通讯,任一进程首先要知道通讯对方的位置,即对方的IP

2)端口号:用来辨别本地的通讯进程,一个本地的进程在通讯时会占用一个端口号,不同的进程端口号不同,因此在通讯之前必须要分配一个没有被访问的端口号

3)连接:指两个进程间的通讯链路

4)半相关:网络中用一个三元组可以在全局唯一标志一个进程,即(协议,本地地址,本地端口号)

5)全相关:一个完整的网间进程通信需要由两个进程组成,并且只能使用一种高层协议。也就是说,不可能通信的一端用TCP协议,而另一端用UDP协议。因此完整的一个网间通信需要一个五元组来标识:

(协议,本地地址, 本地端口号,远地地址,远地端口号)

参照书籍上的用法:

客户端和服务器相连的模式:

1、Server:

Server Side

open a Tcp/Ip socket on a port, listen for a message from a client, and send an echo reply;

this is a simple one-shot listen/reply conversation per client, but it goes into an infinite loop to listen for more clients as long

as this server script runs;

the client may run on a remote machine, or on same computer if it uses 'localhost' for server

from socket import *

# '' = all avaliable interfaces on host

myHost = ''



# listen on a non-reverved port number

myPort = 50007



sockobj = socket(AF_INET, SOCK_STREAM) # make a socket object

sockobj.bind((myHost, myPort)) # bind it to server port number

sockobj.listen(5) # listen, allow 5 pending connects



while True:

    connection, address = sockobj.accept() # wait for next  client connect

    print('Server connected by', address)

    while True:

        data = connection.recv(1024) # read next listen on client socket

        if not data:

            break

        connection.send(b'Echo=' + data)

    connection.close()

2、Client

client side

use sockets to send data to the server, and print server's reply to each message line;

'localhost' means that the server is running on the same machine as the client, which lets us test client and server on one machine;

to test over the internet, run a server on a remote machine , and set serverHost or argv1 to machine's doain name or Ip addr;

Python sockets are a portable bsd socket interface, with object methods for the standard socket calls available in the system's C library.

import sys

from socket import *

serverHost = 'localhost' #server name  

servertPort = 50007 # non-reserved port used by the server 



message = [b'Hello network world'] # require bytes : b'' or str.encode()



if len(sys.argv) > 1:

    servetHost = sys.argv[1]

    if len(sys.argv) > 2:

        message = (x.encode() for x in sys.argv[2:])



sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP/IP socket object

sockobj.connect((serverHost, servertPort)) # connect to server machine + port



for line in message:

    sockobj.send(line)

    data = sockobj.recv(1024)

    print('Client received:', data)



sockobj.close()

e2dcf660be9ff95e8226974c47bb403c.jpg