1 # clientsocket.py
2
3 import socket
4
5 def Main():
6 try:
7 # Address Family : AF_INET (this is IP version 4 or IPv4)
8 # Type : SOCK_STREAM (this means connection oriented TCP protocol)
9 # SOCK_DGRAM indicates the UDP protocol.
10 new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
11 except socket.error, msg:
12 print 'Failed to creat socket. Error code:', str(msg[0]),
13 print 'Error message:', msg[1]
14 return
15 print 'Socket Created'
16
17 host = 'www.baidu.com'
18 port = 80
19 try:
20 remote_ip = socket.gethostbyname(host)
21 except socket.gaierror:
22 print 'Hostname could not be resolved. Exiting.'
23 return
24 print 'Ip address of', host, 'is', remote_ip
25
26 # Connect to remote server
27 new_socket.connect((host, port))
28 print 'Socket Connected to', host, 'on ip', remote_ip
29
30 # Send some data to remote server | socket.sendall(string[, flags])
31 message = 'GET / HTTP/1.1\r\n\r\n'
32 try:
33 new_socket.sendall(message)
34 except socket.error:
35 print 'Send fail.'
36 return
37 print 'Message send successfully.'
38
39 # Receive data | socket.recv(bufsize[, flags])
40 reply = new_socket.recv(4096)
41 print reply
42
43 # Close the socket
44 new_socket.close()
45
46
47 if __name__ == '__main__':
48 Main()
服务器端:
Bind the socket to address.: socket.bind(address)
Listen for connections made to the socket. :socket.listen(backlog)
#! /usr/bin/env python
# serversockethand.py
"""
To handle every connection we need a separate handling code to run along
with the main server accepting connections. One way to achieve this is
using threads. The main server program accepts a connection and creates
a new thread to handle communication for the connection, and then the
server goes back to accept more connections.
"""
import socket
import thread
def Main():
HOST = ''
PORT = 8888
new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created.'
# Bind socket to local host and port
try:
new_socket.bind((HOST, PORT))
except socket.error, msg:
print 'Bind failed. Error code:', str(msg[0]) + 'Message' + msg[1]
return
print 'Socket bind complete'
# Listening on socket
new_socket.listen(10)
print 'Socket now listening..'
# Now keep talking with client
while 1:
# Wait to accept a connection
conn, addr = new_socket.accept()
print 'Connected with', addr[0], ':', str(addr[1])
thread.start_new_thread(clientThread, (conn, ))
new_socket.close()
# Function for handling connections. This will be used to create threads.
def clientThread(conn):
# Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n')
while 1:
data = conn.recv(1024)
if not data:
break
reply = 'OK..' + data
conn.sendall(reply)
conn.close()