`
haoningabc
  • 浏览: 1482891 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

tcp的socket的helloworld

阅读更多
想弄个东西
socket+shm+epoll,想弄个比nginx还快还简单点东西
顺便学一下c的这些宝贝


今天现把nginx的注释都看一遍吧
对于nginx1.0.10
find . -name *.c |xargs grep "/\*.*\*/"|wc -l
2577行
似乎这样更多一些
find . -name *.c |xargs grep "/\*.*"|wc -l
3206
看出ngx_inet.c 是关于socket的,学习一下吧



-----------------------------普通的socket例子
看看server干了什么
/* Create the TCP socket */
/* Construct the server sockaddr_in structure */
/* Bind the server socket */
/* Listen on the server socket */
/* Run until cancelled */
    /* Receive message */
    /* Send bytes and check for more incoming data in loop */
close


看看client干了什么
/* Create the TCP socket */
/* Construct the server sockaddr_in structure */
/* Establish connection */
/* Send the word to the server */
    /* Receive the word back from the server */
close

sh-3.2# cat TCPechoServer.c 
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>

#define MAXPENDING 5    /* Max connection requests */
#define BUFFSIZE 32
void Die(char *mess) { perror(mess); exit(1); }
void HandleClient(int sock) {
		char buffer[BUFFSIZE];
		int received = -1;
		/* Receive message */
		if ((received = recv(sock, buffer, BUFFSIZE, 0)) < 0) {
				Die("Failed to receive initial bytes from client");
		}
		/* Send bytes and check for more incoming data in loop */
		while (received > 0) {
				/* Send back received data */
				if (send(sock, buffer, received, 0) != received) {
						Die("Failed to send bytes to client");
				}
				/* Check for more data */
				if ((received = recv(sock, buffer, BUFFSIZE, 0)) < 0) {
						Die("Failed to receive additional bytes from client");
				}
		}
		close(sock);
}
int main(int argc, char *argv[]) {
            int serversock, clientsock;
            struct sockaddr_in echoserver, echoclient;

            if (argc != 2) {
              fprintf(stderr, "USAGE: echoserver <port>\n");
              exit(1);
            }
            /* Create the TCP socket */
            if ((serversock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
              Die("Failed to create socket");
            }
            /* Construct the server sockaddr_in structure */
            memset(&echoserver, 0, sizeof(echoserver));       /* Clear struct */
            echoserver.sin_family = AF_INET;                  /* Internet/IP */
            echoserver.sin_addr.s_addr = htonl(INADDR_ANY);   /* Incoming addr */
            echoserver.sin_port = htons(atoi(argv[1]));       /* server port */
			 /* Bind the server socket */
			if (bind(serversock, (struct sockaddr *) &echoserver,
									sizeof(echoserver)) < 0) {
					Die("Failed to bind the server socket");
			}
			/* Listen on the server socket */
			if (listen(serversock, MAXPENDING) < 0) {
					Die("Failed to listen on server socket");
			}
			 /* Run until cancelled */
			while (1) {
					unsigned int clientlen = sizeof(echoclient);
					/* Wait for client connection */
					if ((clientsock =accept(serversock, (struct sockaddr *) &echoclient,
													&clientlen)) < 0) {
							Die("Failed to accept client connection");
					}
					fprintf(stdout, "Client connected: %s\n",
									inet_ntoa(echoclient.sin_addr));
					HandleClient(clientsock);
			}
}
sh-3.2# 



h-3.2# cat TCPecho.c 
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>

#define BUFFSIZE 32
void Die(char *mess) {
	perror(mess);
 	exit(1);
}
int main(int argc, char *argv[]) {
		int sock;
		struct sockaddr_in echoserver;
		char buffer[BUFFSIZE];
		unsigned int echolen;
		int received = 0;

		if (argc != 4) {
				fprintf(stderr, "USAGE: TCPecho <server_ip> <word> <port>\n");
				exit(1);
		}
		/* Create the TCP socket */
		if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
				Die("Failed to create socket");
		}
 /* Construct the server sockaddr_in structure */
        memset(&echoserver, 0, sizeof(echoserver));       /* Clear struct */
        echoserver.sin_family = AF_INET;                  /* Internet/IP */
        echoserver.sin_addr.s_addr = inet_addr(argv[1]);  /* IP address */
        echoserver.sin_port = htons(atoi(argv[3]));       /* server port */
        /* Establish connection */
        if (connect(sock,
                    (struct sockaddr *) &echoserver,
                    sizeof(echoserver)) < 0) {
          Die("Failed to connect with server");
        }
  /* Send the word to the server */
        echolen = strlen(argv[2]);
        if (send(sock, argv[2], echolen, 0) != echolen) {
          Die("Mismatch in number of sent bytes");
        }
        /* Receive the word back from the server */
        fprintf(stdout, "Received: ");
        while (received < echolen) {
          int bytes = 0;
          if ((bytes = recv(sock, buffer, BUFFSIZE-1, 0)) < 1) {
            Die("Failed to receive bytes from server");
          }
          received += bytes;
          buffer[bytes] = '\0';        /* Assure null terminated string */
          fprintf(stdout, buffer);
        }
		fprintf(stdout, "\n");
        close(sock);
        exit(0);    
}            
sh-3.2# 

分享到:
评论

相关推荐

    C++ Socket Hello World

    本文将深入探讨"C++ Socket Hello World"这个话题,通过学习基础的Socket编程,你可以理解如何在C++环境下构建简单的TCP客户端(TCPClient)和服务器(TCPServer)。 首先,让我们了解什么是Socket。Socket是操作系统...

    TCP链接HelloWorld级程序

    本篇将深入解析基于.NET 2005下的C++编写的TCP服务器(Server)与客户端(Client)的"HelloWorld"级程序,帮助初学者理解TCP连接的基本原理和实现方式。 首先,TCP是一种面向连接的协议,这意味着在数据传输前,...

    helloworld 小测试

    总的来说,"helloworld 小测试"是一个很好的起点,帮助初学者理解网络编程和服务器开发的基本概念。通过构建和运行这个控制服务器,我们可以学习如何建立网络连接,交换数据,以及如何在服务器端处理这些交互。这些...

    TCP socket 套接字传送文件

    通过TCP/IP协议,我们可以利用socket接口在服务器和客户端之间建立连接并进行文件传输。socket编程是实现这一功能的基础。 在Linux环境下,TCP套接字文件传输涉及以下主要步骤: 1. **创建服务器Socket**: - ...

    c# socket 、TCPClient、TCPListener 用法详解.doc

    s.Send("Hello, World!"); byte[] buffer = new byte[1024]; s.Receive(buffer); ``` 五、结论 C# 中的 Socket 编程提供了一个强大且灵活的网络编程模型,允许开发人员使用 C# 进行网络编程。TCPClient 和 TCP...

    python TCP Socket的粘包和分包的处理详解

    粘包:发送方发送两个字符串”hello”+”world”,接收方却一次性接收到了”helloworld”。 分包:发送方发送字符串”helloworld”,接收方却接收到了两个字符串”hello”和”world”。 虽然socket环境有以上问题,...

    Java socket tcp/ip

    Java套接字(Socket)是Java编程中用于网络通信的核心组件,它基于传输控制协议/因特网协议(TCP/IP)模型。TCP/IP是互联网上应用最广泛的一种通信协议,确保了数据的可靠传输。本篇文章将深入探讨Java中如何使用...

    C++ UDP HelloWorld

    本篇将通过一个简单的"C++ UDP HelloWorld"示例,详细介绍如何在C++中使用UDP套接字进行通信,同时也会涉及VC++开发环境和SOCKET库的应用。 首先,我们来看UDP的特点。与TCP(Transmission Control Protocol)不同...

    socket_socket_

    s.sendall(b'Hello, world') data = s.recv(1024) s.close() print('Received', repr(data)) ``` 以上就是关于socket网络编程的基础知识,包括TCP和UDP的使用。通过理解这些概念和操作,开发者能够构建自己的...

    Netty之helloworld示列

    在本示例中,“Netty之helloworld”旨在为初学者提供一个简单的入门教程,帮助理解Netty的工作原理和基本用法。 首先,Netty的核心概念包括Bootstrap(引导类)、Channel(通道)、Handler(处理器)和EventLoop...

    C#中TCP通讯的实现方法

    byte[] data = Encoding.ASCII.GetBytes("Hello World"); client.Send(data); byte[] buffer = new byte[1024]; int bytesRec = client.Receive(buffer); string receivedData = Encoding.ASCII.GetString(buffer, ...

    QT_的socket_与_Linux_的socket通信Linux

    client.write("Hello world!", 13); } void Client::connectError(QAbstractSocket::SocketError) { char error[100] = "Connect error!"; cout ; } ``` #### 服务器代码 ```cpp int main(void) { int server_...

    tcp收发程序(C#)

    string str = "Hello world!"; try { // 10秒超时发送文本 MyClass.Send(socket, Encoding.UTF8.GetBytes(str), 0, str.Length, 10000); } catch (Exception ex) { // 处理异常 } ``` **Socket.Receive方法** ...

    基于TCP和IP协议编程

    byte[] data = Encoding.ASCII.GetBytes("Hello, World!"); client.Send(data); byte[] buffer = new byte[1024]; int received = client.Receive(buffer); string message = Encoding.ASCII.GetString(buffer, 0, ...

    socket通用客户端

    message = 'Hello, world' s.sendall(message.encode('utf-8')) data = s.recv(1024) print('Received:', data.decode('utf-8')) finally: s.close() ``` 这是一个简单的TCP Socket客户端示例,向本地主机的...

    socket客户端与服务器之间通信

    在TCP/IP协议族中,Socket提供了基于TCP或UDP的通信机制。通过Socket,可以建立两个进程之间的连接,并在其间进行双向的数据传输。 ### 服务器端编程 在服务器端代码中,我们首先初始化Winsock库,确保系统能够...

    分布式 socket编程

    byte[] data = Encoding.UTF8.GetBytes("Hello World!"); clientSocket.Send(data); byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); string receivedData = Encoding.UTF...

    tcp_client.cpp.tar.gz_world

    1. **套接字编程**:TCP客户端需要使用套接字API(如在Unix系统中的socket()、connect()等函数)来建立与服务器的连接。套接字是网络通信的基本单位,它提供了进程间通信的能力。 2. **IP地址与端口号**:客户端...

    PHP和SOCKET

    socket_write($socket, "Hello, World!", strlen("Hello, World!")); ``` - **socket_close()**:关闭Socket连接。 ```php socket_close($socket); ``` #### 四、示例代码解析 下面是一个简单的PHP Socket...

    java udp and tcp

    byte[] b = "Hello World!".getBytes(); DatagramPacket dp = new DatagramPacket(b, b.length, InetAddress.getByName("localhost"), 3000); ``` 3. **发送数据报**:通过DatagramSocket对象的send方法发送数据...

Global site tag (gtag.js) - Google Analytics