C語言 編寫的乙個簡單的Server Client

2021-05-26 15:14:18 字數 2543 閱讀 1472

伺服器:

#include #include #pragma comment(lib, "ws2_32.lib")

/******************************************

函式名稱:server

輸入引數:

函式功能:

*******************************************/

void main()

// 建立socket

socket server;

server = socket(af_inet, sock_stream, ipproto_tcp);

if ( server == invalid_socket )

// 繫結socket

int iret;

sockaddr_in service;

service.sin_family = af_inet;

service.sin_addr.s_addr = inet_addr( "192.168.102.88" );

service.sin_port = htons( 27015 );

iret = bind(server, (sockaddr*) &service, sizeof(service));

if (socket_error == iret)

// 監聽 socket

if ( listen( server, 1 ) == socket_error )

printf( "error listening on socket. \n");

// 接受連線

socket acceptsocket;

printf("waiting for client to connect... \n");

while (1)

printf( "client connected. \n");

server = acceptsocket;

break; }

// 傳送接受資料

int isent;

int irecv = socket_error;

char sendbuf[32] = "server: sending data.";

char recvbuf[32] = "";

irecv = recv( server, recvbuf, 32, 0);

printf("bytes recv: %d \n", irecv);

isent = send( server, sendbuf, strlen(sendbuf), 0);

printf("bytes sent: %d \n", isent);

return;

}

客戶端:

#include #include #pragma comment(lib, "ws2_32.lib")

/******************************************

函式名稱:

輸入引數:client

函式功能:

*******************************************/

void main()

// 建立套接字.

socket client;

client = socket( af_inet, sock_stream, ipproto_tcp );

if (client == invalid_socket)

// 連線到伺服器.

int iret;

sockaddr_in clientservice;

clientservice.sin_family = af_inet;

clientservice.sin_addr.s_addr = inet_addr("192.168.102.88");

clientservice.sin_port = htons( 27015 );

iret = connect( client, (sockaddr*) &clientservice, sizeof(clientservice));

if (iret == socket_error)

// 傳送並接收資料.

int isent;

int irecv = socket_error;

char sendbuf[32] = "client: sending data.";

char recvbuf[32] = "";

isent = send( client, sendbuf, strlen(sendbuf), 0 );

printf( "bytes sent: %d \n", isent );

while( irecv == socket_error )

if (irecv < 0)

return;

printf( "bytes recv: %d \n", irecv ); }

return;

}

C語言編寫乙個簡單的三子棋

如何變現乙個三子棋遊戲呢?1.首先每乙個遊戲都需要有乙個選單函式進行選擇遊戲的開始以及結束。2.我們先分析下三子棋遊戲的棋盤是乙個3x3的九宮格,因此需要建立乙個3x3的陣列。3.設定乙個初始化函式,對陣列進行初始化,將所有的下棋位置初始為空。4.建立乙個列印棋盤函式,顯示棋盤。5.設定乙個玩家下棋...

編寫乙個簡單的shell

include include include include include include include include void getloginname void gethostname void getdir p printf s p int main char argv 32 char...

編寫乙個簡單的死鎖

public class dead lock1 class runnable1 implements runnable catch exception e class runnable2 implements runnable catch exception e obj1 和 obj2 都是屬於類的...