close

這邊主要是Client端對Server端的傳輸協議方法

獲取Server端IP Address

import socket

import sys

 

serverHost = 'www.yahoo.com.tw'

try:

    #socket.gethostbyname的函式是用來獲取遠端主機的IP Address

    server_ip = socket.gethostbyname(serverHost) 

except socket.gaierror:

    print('Hostname could not be resolved. Exiting!')

    sys.exit()

    print('IP Address of ' + serverHost + ' is ' + server_ip)

 

Client端建立Socket及Socket接異常訊息

import socket

import sys

#socket.socket(Address Family, Type)

#Address Family分為兩種AF_INET及AF_UNIX

#AF_INET: 用於Internet程序間通訊

#AF_UNIX: 用於同一台機器程序間通訊

#Type分為兩種套接字型別SOCK_STREAM及SOCK_DGRAM

#SOCK_STREAM: 流式套接字, 主要用於TCP協定

#SOCK_DGRAM: 資料包套接字, 主要用於UDP協定

try:

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #建構Internet通訊, 並採用TCP協定

    print('Socket Created!')

except socket.error:

    print('Failed to create socket. ' +str(socket.error))

    sys.exit()

 

連線伺服器上特定的port

import socket

import sys

 

serverHost = 'www.yahoo.com.tw'

port = 80

try:

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #建構Internet通訊, 並採用TCP協定

    print('Socket Created!')

    #socket.gethostbyname的函式是用來獲取遠端主機的IP Address

    server_ip = socket.gethostbyname(serverHost) 

    print('IP Address of ' + serverHost + ' is ' + server_ip)

    #連線到Server端

    s.connect((server_ip, port))

    print('Socket Connected to ' + serverHost + ' on ip ' + server_ip)

except socket.gaierror:

    print('Hostname could not be resolved. Exiting!')

    sys.exit()

 

輸出結果如下:

 

傳送資料與接收資料

import socket

import sys 

 

serverHost = 'www.yahoo.com.tw'

port = 80
    
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print ('Socket Created')
    server_ip = socket.gethostbyname(serverHost)
    print('IP Address of ' + serverHost + ' is ' + server_ip)
    s.connect((server_ip, port))
    print('Socket Connected to ' + serverHost + ' on ip ' + server_ip)
    message = "GET / HTTP/1.1\r\n\r\n"
    bytM = message.encode()
    s.sendall(bytM)
    print('Message send successfully')
    recvData = s.recv(4096)
    print(recvData)

    s.close()

except socket.error:
    print('Failed!')
    sys.exit()

 

輸出結果如下:

 

arrow
arrow
    創作者介紹
    創作者 楓綺 的頭像
    楓綺

    K_程式人

    楓綺 發表在 痞客邦 留言(0) 人氣()