Simple socket communication and socket Communication

Source: Internet
Author: User
Tags socket error

Simple socket communication and socket Communication

Rough and simple first version, more features to be used as a trainer
/* ===================================================== ============================================================ Name: server. cAuthor: kingVersion: Copyright: Your copyright noticeDescription: Hello World in C, ansi-style ========================================== ======================================================= * /# include <stdlib. h> # include <pthread. h> # include <sys/socket. h> # include <sys/types. h> # include <netinet/in. h> # include <arpa/inet. h>/* inet (3) functions */# include <stdlib. h> # include <errno. h> # include <stdio. h> # include <string. h> int handle (int point); int main (void) {int sfd, ind; struct sockaddr_in addr; struct sockaddr_in clent; char resv [1024], sendbuf [1024]; char buf [1024]; char * myaddr = "192.168.231.128"; int ret; // set socklen_t lent; int pid; addr. sin_family = AF_INET; // IPv4 Internet protocolsaddr. sin_port = htons (5050); // enter the server port number addr. sin_addr.s_addr = inet_addr (myaddr); // INADDR_ANY indicates the IP address of the Local Machine. // retrieve the socket descriptor, IPV4asdprintf ("socket start \ n"); sfd = socket, 0); if (sfd <0) {printf ("socket error \ n"); return-1;} printf ("bind start \ n "); // link the socket child to the specified port if (bind (sfd, (struct sockaddr *) & addr, sizeof (struct sockaddr) <0) {printf ("bind error \ n"); return-1 ;}// listen to the sub-printf ("listen start \ n"); if (listen (sfd, 1024) <0) {printf ("listen error \ n"); return-1 ;}for (;;) {// accept the message printf ("accept start \ n") from the client; memset (& clent, 0, sizeof (clent); lent = sizeof (clent ); ind = accept (sfd, (struct sockaddr *) & clent, & lent); if (ind <0) {printf ("accept error % d \ n", ind ); return-1;} printf ("infor \ n"); printf ("clent addr % s porit % d \ n", inet_ntop (AF_INET, & clent. sin_addr, buf, sizeof (buf), ntohs (clent. sin_port); pid = fork (); if (pid = 0) {// sub-process close (sfd); handle (ind);} else if (pid <0) {// errorclose (ind);} else {// parent process} return EXIT_SUCCESS;} int handle (int point) {int retn; char buf [1024]; for (;) {retn = read (point, buf, sizeof (buf); if (retn <0) {printf ("read error \ n "); close (point); break;} else if (retn = 0) {printf ("client exit \ n"); close (point); break;} printf ("client: % s \ n ", buf); if (strcmp (" exit ", buf) = 0) {printf (" exit \ n "); close (point ); return 0 ;}} return 0 ;}




/* ============================================================================ Name        : client.c Author      : king Version     : Copyright   : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */#include <stdio.h>#include <stdlib.h>#include <sys/socket.h>#include  <netinet/in.h>#include  <arpa/inet.h>       /* inet(3) functions */int handle(int fd);int main(void) {    int nsd;    char buf[1024];    char * myaddr = "192.168.231.128";    struct sockaddr_in addr;    printf("welcome to echo client\n");    nsd = socket(AF_INET, SOCK_STREAM, 0);    printf("connect start1 \n");    //bzero(addr, sizeof(*addr));    memset(&addr,0,sizeof(addr));    printf("connect start2 \n");    addr.sin_family = AF_INET;    addr.sin_port = htons(5050);    addr.sin_addr.s_addr=inet_addr(myaddr);    printf("connect start3 \n");    if (connect(nsd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) < 0) {        printf("connect error \n");        return -1;    }    sleep(5);    printf("handle start\n");    handle(nsd);    close(nsd);    return EXIT_SUCCESS;}int handle(int fd) {    char sendl[1024], rev[1024];    int retn;    for (;;) {        memset(sendl,0,sizeof(sendl));        memset(rev,0,sizeof(rev));        if (fgets(sendl, 1024, stdin) == NULL) {            break;        }        //        printf("wirte start\n");        write(fd, sendl, strlen(sendl));        read(fd, rev,strlen(rev));    }    return 0;}

 

 
Although I have been writing a program for several years, I still feel that the technology is not enough. So I reviewed the socket,
Errors encountered during this period have not been compiled:
Connect and accept
Because they do not have a deep understanding of the parameters of these two functions, an error occurs.

 

Int connect (int sockfd, const struct sockaddr * addr,
Socklen_t addrlen );

Remember that the value must be addrlen.

Accept socklen_t * addrlen is a pointer

I thought they were the same, and the results were adjusted for an hour.

You still need to work hard.


Layman c ++ simple code socket communication

# Include "stdafx. h"

# Include <Winsock2.h>
# Include <stdio. h>
# Include <stdlib. h>

# Define PORT 5000

Int main (int argc, char * argv [])
{

Int port = PORT;
WSADATA wsaData;
SOCKET sListen, sAccept;

Int iLen;

Int iSend;

Char buf [] = "Hello! ";
// Server and customer address
Struct sockaddr_in serv, cliet; // declare two address struct Variables

If (WSAStartup (MAKEWORD (2, 2), & wsaData )! = 0)
{
Printf ("Winsock load failed \ n ");
// Return;
} // Load the socket Library

// Create a socket AD_INET (IPV4 protocol) SOCK_STREAM (TCP protocol)
SListen = socket (AF_INET, SOCK_STREAM, 0 );

// Determine whether the task fails.
If (sListen = INVALID_SOCKET)
{
Printf ("socket failed: % d \ n", WSAGetLastError ());
Return;
}

Assign a value to the address struct of the server
Serv. sin_family = AF_INET; // it must be the same as when creating a socket (socket)
Serv. sin_port = htons (port); // convert the port htons to the network byte order
Serv. sin_addr.s_addr = htonl (INADDR_ANY); // convert the bound address htonl to the network byte order.
// INADDR_ANY default NIC address local machine

If (bind (sListen, (LPSOCKADDR) & serv, sizeof (serv) = SOCKET_ERROR)
{
Printf ("bind () failed: % d \ n", WSAGetLastError ());
Return;
} // Bind the address and determine whether it is successful

If (listen (sListen, 5) = SOCKET_ERROR)
{
Printf ("listen () failed: % d \ n", WSAGetLastError ());
Return;
} // Listen and determine whether the request is successful

ILen = sizeof (cliet); to obtain the length of the address struct, the accept function needs

// Circular simplified customer connection
While (1)
{
SAccept = accept (sListen, (struct sockaddr *) & cliet, & iLen );

Java simple socket communication

The simplest way is to replace the dins. readUTF () method with the dins. readLine () method. The error is caused by unexpected termination when the stream is reached.
You will find that the readLine () method is obsolete and is not recommended.

The conventional method is to use
BufferedReader br = new BufferedReader (new InputStreamReader (ins ));
To replace DataInputStream

Good luck!

Related Article

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.