TCP编程的 服务器端 一般步骤是:
1、创建一个socket,用函数socket() ;
2、设置socket属性,用函数setsockopt(); * 可选
3、绑定IP地址、端口等信息到socket上,用函数bind() ;
4、开启监听,用函数listen() ;
5、接收客户端上来的连接,用函数accept() ;
6、收发数据,用函数send() 和recv() ,或者read() 和write();
7、关闭网络连接;
8、关闭监听;
TCP编程的 客户端 一般步骤是:
1、创建一个socket,用函数socket() ;
2、设置socket属性,用函数setsockopt();* 可选
3、绑定IP地址、端口等信息到socket上,用函数bind();* 可选
4、设置要连接的对方的IP地址和端口等属性;
5、连接服务器,用函数connect() ;
6、收发数据,用函数send() 和recv() ,或者read() 和write() ;
7、关闭网络连接;
Tcp的多用户连接:
# include < stdio. h> # include < string . h> # include < unistd. h> # include < ctype . h> # include < sys/ socket . h> # include < netinet/ in. h> # include < arpa/ inet. h> # include < errno . h> # include < stdlib. h> # include < signal . h> # define MAXLINE 800int port = 8000; int main( void ) {
struct sockaddr_in sin ;
struct sockaddr_in pin;
int listen_fd;
int conn_fd;
int sock_fd;
int nready;
int maxi;
int max ;
int client[ FD_SETSIZE] ;
int address_size = sizeof ( pin) ;
char buf[ MAXLINE] ;
char str[ INET_ADDRSTRLEN ] ;
int i;
int len;
int n;
int ret;
bzero( & sin , sizeof ( sin ) ) ;
sin . sin_family = AF_INET ;
sin . sin_addr. s_addr = INADDR_ANY ;
sin . sin_port = htons ( port) ;
signal ( SIGPIPE, SIG_IGN ) ;
signal ( SIGCHLD, SIG_IGN ) ;
listen_fd = socket ( AF_INET , SOCK_STREAM , 0) ;
if ( - 1 = = listen_fd)
{
perror ( "call
to socket" ) ;
exit ( 1) ;
}
n = bind ( listen_fd, ( struct sockaddr * ) & sin , sizeof ( sin ) ) ;
if ( - 1 = = n)
{
perror ( "call
to bind" ) ;
exit ( 1) ;
}
n = listen ( listen_fd, 20) ;
if ( - 1 = = n)
{
perror ( "call
to listen" ) ;
exit ( 1) ;
}
printf ( "Accepting
connections...\n" ) ;
while ( 1)
{
conn_fd = accept ( listen_fd, ( struct sockaddr * ) & pin, & address_size) ;
n = fork( ) ;
if ( - 1 = = n) {
perror ( "call
to fork" ) ;
转载于:https://www.cnblogs.com/llinzuxin/archive/2012/10/26/2950475.html