SOCKET TCP 发送和接收示例代码

发送端代码:

// socket used to send SOCKET sockSend = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // local address SOCKADDR_IN addrSend; addrSend.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrSend.sin_port = htons(5120); addrSend.sin_family = AF_INET; SOCKADDR_IN addrRecv; // remote address addrRecv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrRecv.sin_port = htons(5000); addrRecv.sin_family = AF_INET; // message buffer CHAR szMsg[10] = ""; // bind the address for sending socket bind(sockSend, (LPSOCKADDR)&addrSend, sizeof(SOCKADDR_IN)); // connect to the remote host connect(sockSend, (PSOCKADDR)&addrRecv, sizeof(SOCKADDR_IN)); LOOP: // input the message to be sent cout << "Input data: "; cin >> szMsg; // send the message send(sockSend, szMsg, 10, 0); // whether exit if(*szMsg != 'e') goto LOOP; // close socket closesocket(sockSend);

接收端代码:

// socket used receive SOCKET sockRecv = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // remote address SOCKADDR_IN addrSend; int iLen = sizeof(SOCKADDR_IN); // local address SOCKADDR_IN addrRecv; addrRecv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrRecv.sin_port = htons(5000); addrRecv.sin_family = AF_INET; // message buffer CHAR szMsg[10] = ""; // recvfrom() return value int retRecv; // bind the address for the receiving socket bind(sockRecv, (LPSOCKADDR)&addrRecv, sizeof(SOCKADDR_IN)); // set the socket to listen mode listen(sockRecv, 5); // wait for the client to connect CONNECT: SOCKET sockConn = accept(sockRecv, (PSOCKADDR)&addrSend, &iLen); if(INVALID_SOCKET == sockConn) { cout << "accept() causes error, code: " << WSAGetLastError() << endl; goto EXIT1; } cout << "Connection established: " << inet_ntoa(addrSend.sin_addr) << ":" << ntohs(addrSend.sin_port) << endl; RECV: // receive message retRecv = recv(sockConn, szMsg, 10, 0); // output the receive message cout << "Receive message: " << szMsg << endl; cout << "recv() returns: " << retRecv << endl; if(0 == retRecv) { cout << "Connection closed: " << inet_ntoa(addrSend.sin_addr) << ":" << ntohs(addrSend.sin_port) << endl; closesocket(sockConn); goto CONNECT; } // whether exit if(*szMsg != 'q') goto RECV; // close socket EXIT: closesocket(sockConn); EXIT1: closesocket(sockRecv);

注:去掉了容错代码

你可能感兴趣的:(socket,tcp,Stream,buffer,input,output)