Linux C++ Socket Example with Client Server and Mulit-Threading

Aim
The aim of this Linux C++ example is to create simple client/server socket communication and multi-threading program on Linux. This shows the basics such as binding, listening and accepting sockets for Servers and connecting sockets for clients. Once the server accepts a socket, a thread is spawned to handle it. The threads are C++ POSIX threads. This is the simplest Linux C++ multi-threaded socket example you can find. Please leave any comments or questions at the end of this tutorial and I will endeavour to answer them. For a forking server look at Linux C++ Forking Server and Client Example.

Assumptions
This article assumes that you have a Linux based C++ compiler installed and configured. You can use cygwin if you do not have a Linux environment.

Bind to the local address and port using bind(). For a server use INADDR_ANY as the address.

listen() for connections.

Go into a loop and accept connections usin accept(). Spawn threads (pthread_create) to handle these connections, so you can accept more connections.

Read and write to the socket. within the thread.

close()

When you are done, close the server socket using close()

Steps required for a client socket

Initialize the socket using socket().

Set any options such as blocking etc using setsockopt().

Connect to the remote host using connet(). Supply address and port here.

Read and write to the socket.
close()
Write and compile the Server

The server listens on port 1101 for a connection. When it receives a connection it creates a thread via pthread_create to handle it. This thread then reads from the socket, appends " SERVER ECHO" to it and sends it back to the client. As the server doesn't require an IP address, we assign INADDR_ANY to the sockaddr_in struct. Save this code as LinSever.cpp.

Hey , i would like to clarify regarding the server coding. You stated that to close the server port , we are to make use of close()? I tried using csock.close() but it dosnt seem to work for me. Am i getting it wrong? I used hsock.close() but im facing the same problem

Hello Sir,I am new for android. i trying for data transfer between computer and mobile phone via USB cable.Communication can be done two way:1) The first way is Socket,Protocol so like2) The Second way is Using USB functionsie, can be take example for in android USB HOST and USB Accessory Methods and in JAVA can also have JAVA HOST methods.Please sir,If you will have this code means send me sir,otherwise give some ideas and techniques of code..thank you sir…

Problems:1) The program is a C program not a C++ program (well, it's both).2) It makes no usage of C++ features.3) The code is confusing to read unless you know what's going on.4) The program creates a new thread per client instead of using select/pselect to handle multiple clients.