socket

Server side

define sockaddr_in
structure sockaddr_in serveraddr, clientaddr

new a socket
server_socket = socket (AF_INET, SOCK_STREAM, 0)

setup serveraddr
serveraddr.sin_family
serveraddr.sin_port
serveraddr.sin_addr.s_addr = htons(INADDR_ANY)

bind serveraddr to server_socket
bind(server_socket, (struct sockaddr *) &serveraddr, sizeof(serveraddr)

set up listen
listen(server_socket, LENGTH_OF_LISTEN_QUEUE)

server loop cycle, never exit

no need to setup in server loop
clientaddr.sin_family, clientaddr.sin_port, clientaddr.sin_addr.s_addr
client_socket is generate by accept

client_socket = accetp(server_socket, (struct sockaddr *) &clientaddr, sizeof(clientaddr))

sent some information to client
send(client_socket, buf, BUFFER_SIZE, 0)

close client_socket after send inforation to client
close(client_socket)

 

 

 

 


Client side

define sockaddr_in
struct sockaddr_in clientaddr, serveraddr

define buffer char array
char buf[BUFFER_SIZE]

new a socket
client_socket  =  socket(AF_INET, SOCK_STREAM, 0)

setup clientaddr
clientaddr.sin_family
clientaddr.sin_port
clientaddr.sin_addr.s_addr

setup serveraddr
serveraddr.sin_family
serveraddr.sin_port
serveraddr.sin_addr.s_addr

inet_aton(argv[1], &serveraddr.sin_addr)
serveraddr.sin_addr.s_addr = inet_aton("127.0.0.1")

bind clientaddr to client_socket
bind(client_socket, (struct sockaddr*)&clientaddr, sizeof(clientaddr))

connect client_socket to serveraddr
connect(client_socket, (struct sockaddr*)&serveraddr, sizeof(serveraddr))

receive information from server side
recv(client_socket, buf, BUFFER_SIZE, 0)

 

posted @ 2012-10-28 19:45  greencolor  阅读(205)  评论(0编辑  收藏  举报