Note the simplest programming of socket server and client (C and Python)

Source: Internet
Author: User
Tags htons

C version:

//////////////////////////////////////// /// // Server

# Include "winsock2.h"

# Include <stdio. h>
# Include <stdlib. h>
# Define default_port 6789.
# Define default_count 25
# Define default_buffer 4096.

Int iport = default_port; // port to listen for clients on
Bool binterface = false, // listen on the specified Interface
Brecvonly = false; // recive data only; don't echo back
Char szaddress [128]; // interface to listen for clients on

Struct mylistensocket
{
Char clientip [255];
Int port;
Socket consocket;
};

//
// Fuction: clientthread
//
// Descripton:
// This function is called as a thread, and it handles a given
// Client connection. The parameter passed in is the socket
// Handle returned frome an accept () call. This function reads
// Data from the client and writes it back.
//
DWORD winapi clientthread (lpvoid lpparam)
{
Mylistensocket * sock = (mylistensocket *) lpparam;
Char szbuff [default_buffer];
Int ret,
Nleft,
Idx;
While (1)
{
// Perform a blocking Recv () call
//
Ret = Recv (sock-> consocket, szbuff, default_buffer, 0 );
If (ret = 0) // graceful close
Break;
Szbuff [RET] = '/0 ';
Printf ("Recv from (% s, % d): '% s'/N", sock-> clientip, sock-> port, szbuff );
Send (sock-> consocket, "received", 10, 0 );

}
Return 0;
}
//
// Function: Main
//
// Description:
// Main thread of execution. initialize WinSock, parse
// Command line arguments, create the listening socket, bind
// To the lcoal address, and wait for client connections.
//
Int main (INT argc, char ** argv)
{
Wsadata WSD;
Socket slisten,
Sclient;
Int iaddrsize;
Handle hthread;
DWORD dwthreadid;
Struct sockaddr_in local,
Client;
Struct mylistensocket * MLS = new mylistensocket ();
If (wsastartup (makeword (2, 2), & WSD )! = 0)
{
Printf ("failed to load Winsock! /N ");
Return 1;
}
// Crate our listening socket
//
Slisten = socket (af_inet, sock_stream, ipproto_ip );
If (slisten = socket_error)
{
Printf ("socket () failed: % d/N", wsagetlasterror ());
Return 1;
}
// Select the local interface, and bind to it
//
If (binterface)
{
Local. sin_addr.s_addr = inet_addr (szaddress );
}
Else
Local. sin_addr.s_addr = htonl (inaddr_any );
Local. sin_family = af_inet;
Local. sin_port = htons (iport );

If (BIND (slisten, (struct sockaddr *) & Local, sizeof (local) = socket_error)
{
Printf ("BIND () failed: % d/N", wsagetlasterror ());
Return 1;
}
Listen (slisten, 8 );
//
// In a continuous loop, wait for incoming clients. Once one
// Is detected, create a thread and pass teh handle off to it.
//
While (1)
{
Iaddrsize = sizeof (client );
Sclient = accept (slisten, (struct sockaddr *) & client, & iaddrsize );
If (sclient = invalid_socket)
{
Printf ("accept () failed: % d/N", wsagetlasterror ());
Break;
}
Printf ("accepted clients: % s: % d/N", inet_ntoa (client. sin_addr), ntohs (client. sin_port ));
Strcpy (MLS-> clientip, inet_ntoa (client. sin_addr ));
MLS-> Port = ntohs (client. sin_port );
MLS-> consocket = sclient;
Hthread = createthread (null, 0, clientthread, (lpvoid) MLS, 0, & dwthreadid );
If (hthread = NULL)
{
Printf ("createthread () failed: % d/N", wsagetlasterror ());
Break;
}
Closehandle (hthread );
}
Closesocket (slisten );
Wsacleanup ();
Return 0;
}

 

 

/// // Client end

# Include <winsock2.h>
# Include "stdio. H"

Int Port = 6789;
Char szip [255] = "127.0.0.1 ";

Int _ tmain (INT argc, _ tchar * argv [])
{
Socket Client;
Wsadata WSA;
Sockaddr_in ADDR;
If (wsastartup (makeword (2, 2), & WSA )! = 0)
Printf ("wsastartup error! /N ");
Client = socket (af_inet, sock_stream, ipproto_tcp );
ADDR. sin_family = af_inet;
ADDR. sin_port = htons (port );
ADDR. sin_addr.s_addr = inet_addr (szip );
If (connect (client, (struct sockaddr *) & ADDR, sizeof (ADDR ))! = 0)
Printf ("Connect error/N ");
For (INT I = 0; I <10; I ++)
{
Send (client, szip, strlen (szip), 0 );
Sleep (10 );
}

Wsacleanup ();

Getchar ();

Return 0;
}

 

 

 

Python version:

/// // Server

From socket import *

Host = '2017. 0.0.1'
Listenport = 50001
Server = socket (af_inet, sock_stream)
Server. BIND (host, listenport ))
Server. Listen (10)
While true:
Conn, address = server. Accept ()
Print 'server connceted by ', address
While true:
Data = conn. Recv (512)
If not data:
Break
Print address, ':', Data
Conn. Send ('echo from server: '+ data)
Conn. Close ()

 

 

/// // Client

From socket import *
Host = '2017. 0.0.1'
SERVERPORT = 50000
MSG = 'How are you! '
Client = socket (af_inet, sock_stream)
Client. Connect (host, SERVERPORT ))
For CH in MSG:
Client. Send (CH)
Data = client. Recv (1024)
Print 'receive from server: ', Data
Client. Close ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.