導航:首頁 > 源碼編譯 > socket程序源碼

socket程序源碼

發布時間:2024-09-18 02:37:00

『壹』 linux C語言編程,socket實現的即使通訊系統

Socket通信創建步驟:

(1)通過socket()函數創建socket
(2)通過bind函數綁定socket於設備地址
(3)進行讀寫操作read/recv/recvfrom write/send/sendto
(4)close方法關閉套接字


例子如下:

test1.c

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>

intmain(void)
{
//createsocket
intfd=socket(AF_INET,SOCK_DGRAM,0);
if(fd==-1)
{
perror("socket ");
exit(-1);
}
printf("socketfd=%d ",fd);

//buildconnectionaddress
structsockaddr_inaddr;
addr.sin_family=AF_INET;
addr.sin_port=htons(6666);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");

intr;
r=bind(fd,(structsockaddr*)&addr,sizeof(addr));
if(r==-1)
{
perror("bind");
close(fd);
exit(-1);
}
printf("bindaddresssuccessful! ");
//acceptorsendmessage
charbuf[255];
structsockaddr_infrom;
socklen_tlen;
len=sizeof(from);
塵梁空while(1)
{
r=recvfrom(fd,buf,sizeof(buf)-1,0,(structsockaddr*)&from,&len);
if(r>0)
{
buf[r]=0;
printf("Themessagefrom%sis:%s ",inet_ntoa(from.sin_addr),buf);
}
else
{
break;
}
}
//closesocket
close(fd);
return0;
}

test2.c

java">#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

intmain(void)
{
//createsocket
intfd=socket(AF_INET,SOCK_DGRAM,0);
if(fd==-1)
{
perror("socket");
exit(-1);
}
printf("createsocketOK! ");
//createansendaddress
structsockaddr_inaddr={};
addr.sin_family=AF_INET;
addr.sin_port=htons(6666);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
//
intr;
派瞎charbuf[255];
while(1)
{
r=read(0,buf,sizeof(buf)-1);
if(r<=0)
break;
sendto(fd,buf,r,0,(structsockaddr*)&addr,sizeof(addr));
}
//closesocket
渣凳close(fd);
return0;
}

先運行test1.c,然後運行test2.c,在test2.c運行後輸入內容,在test1.c所在終端中就會顯示信息

運行結果如下:

『貳』 如何編寫一個利用Socket通信的程序

設計思路

本例包括一個伺服器端程序和一個客戶端程序。客戶端程序可以放到多個計算機上運行,同時與伺服器端進行連接通信。

本例的重點,一是演示客戶端與伺服器端如何通信;二是當有多個客戶端同時連接到伺服器端時,伺服器端如何識別每個客戶端,並對請求給出相應的回復。為了保證一個客戶端斷開連接時不影響其它客戶端與伺服器端的通信,同時保證伺服器端能夠正確回復客戶端的請求,在本例中聲明了一個記錄類型:

type
client_record=record
CHandle: integer; //客戶端套接字句柄
CSocket:TCustomWinSocket; //客戶端套接字
CName:string; //客戶端計算機名稱
CAddress:string; //客戶端計算機IP地址
CUsed: boolean; //客戶端聯機標志
end;

利用這個記錄類型數據保存客戶端的信息,同時保存當前客戶端的連接狀態。其中,CHandle保存客戶端套接字句柄,以便准確定位每個與伺服器端保持連接的客戶端;Csocket保存客戶端套接字,通過它可以對客戶端進行回復。Cused記錄當前客戶端是否與伺服器端保持連接。

下面對組件ServerSocket和ClientSocket的屬性設置簡單說明。

ServerSocket的屬性:

· Port,是通信的埠,必須設置。在本例中設置為1025;

· ServerTypt,伺服器端讀寫信息類型,設置為stNonBlocking表示非同步讀寫信息,本例中採用這種方式。

· ThreadCacheSize,客戶端的最大連接數,就是伺服器端最多允許多少客戶端同時連接。本例採用默認值10。

其它屬性採用默認設置即可。

ClientSocket的屬性:

· Port,是通信的埠,必須與伺服器端的設置相同。在本例中設置為1025;

· ClientType,客戶端讀寫信息類型,應該與伺服器端的設置相同,為stNonBlocking表示非同步讀寫信息。

· Host,客戶端要連接的伺服器的IP地址。必須設置,當然也可以在代碼中動態設置。

其它屬性採用默認設置即可。
程序源代碼:

· 伺服器端源碼(uServerMain.pas):

unit uServerMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ScktComp, ToolWin, ComCtrls, ExtCtrls, StdCtrls, Buttons;
const
CMax=10; //客戶端最大連接數
type
client_record=record
CHandle: integer; //客戶端套接字句柄
CSocket:TCustomWinSocket; //客戶端套接字
CName:string; //客戶端計算機名稱
CAddress:string; //客戶端計算機IP地址
CUsed: boolean; //客戶端聯機標志
end;
type
TfrmServerMain = class(TForm)
ServerSocket: TServerSocket;
ControlBar1: TControlBar;
ToolBar1: TToolBar;
tbConnect: TToolButton;
tbClose: TToolButton;
tbDisconnected: TToolButton;
Edit1: TEdit;
Memo1: TMemo;
StatusBar: TStatusBar;
procere tbConnectClick(Sender: TObject);
procere tbDisconnectedClick(Sender: TObject);
procere ServerSocketClientRead(Sender: TObject;Socket: TCustomWinSocket);
procere ServerSocketListen(Sender: TObject;Socket: TCustomWinSocket);
procere ServerSocketClientConnect(Sender: TObject;Socket: TCustomWinSocket);
procere ServerSocketClientDisconnect(Sender: TObject;Socket: TCustomWinSocket);
procere tbCloseClick(Sender: TObject);
procere FormCreate(Sender: TObject);
procere FormClose(Sender: TObject; var Action: TCloseAction);
procere ServerSocketGetSocket(Sender: TObject; Socket: Integer;
var ClientSocket: TServerClientWinSocket);
procere ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
private
{
Private declarations
}
public
{
Public declarations
}
session: array[0..CMax] of client_record; //客戶端連接數組
Sessions: integer; //客戶端連接數
end;
var
frmServerMain: TfrmServerMain;
implementation
{$R *.DFM}
//打開套接字連接,並使套接字進入監聽狀態
procere TfrmServerMain.tbConnectClick(Sender: TObject);
begin
ServerSocket.Open ;
end;
//關閉套接字連接,不再監聽客戶端的請求
procere TfrmServerMain.tbDisconnectedClick(Sender: TObject);
begin
ServerSocket.Close;
StatusBar.Panels[0].Text :='伺服器套接字連接已經關閉,無法接受客戶端的連接請求.';
end;
//從客戶端讀取信息
procere TfrmServerMain.ServerSocketClientRead(Sender: TObject;Socket: TCustomWinSocket);
var
i:integer;
begin
//將從客戶端讀取的信息添加到Memo1中
Memo1.Lines.Add(Socket.ReceiveText);
for i:=0 to sessions do
begin
//取得匹配的客戶端
if session[i].CHandle = Socket.SocketHandle then
begin
session[i].CSocket.SendText('回復客戶端'+session[i].CAddress+' ==> '+Edit1.Text);
end;
end;
end;
//伺服器端套接字進入監聽狀態,以便監聽客戶端的連接
procere TfrmServerMain.ServerSocketListen(Sender: TObject;Socket: TCustomWinSocket);
begin
StatusBar.Panels[0].Text :='等待客戶端連接...';
end;
//當客戶端連接到伺服器端以後
procere TfrmServerMain.ServerSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
var
i,j:integer;
begin
j:=-1;
for i:=0 to sessions do
begin
//在原有的客戶端連接數組中有中斷的客戶端連接
if not session[i].CUsed then
begin
session[i].CHandle := Socket.SocketHandle ;//客戶端套接字句柄
session[i].CSocket := Socket; //客戶端套接字
session[i].CName := Socket.RemoteHost ; //客戶端計算機名稱
session[i].CAddress := Socket.RemoteAddress ;//客戶端計算機IP
session[i].CUsed := True; //連接數組當前位置已經佔用
Break;
end;
j:=i;
end;
if j=sessions then
begin
inc(sessions);
session[j].CHandle := Socket.SocketHandle ;
session[j].CSocket := Socket;
session[j].CName := Socket.RemoteHost ;
session[j].CAddress := Socket.RemoteAddress ;
session[j].CUsed := True;
end;
StatusBar.Panels[0].Text := '客戶端 '+Socket.RemoteHost + ' 已經連接';
end;
//當客戶端斷開連接時
procere TfrmServerMain.ServerSocketClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
var
i:integer;
begin
for i:=0 to sessions do
begin
if session[i].CHandle =Socket.SocketHandle then
begin
session[i].CHandle :=0;
session[i].CUsed := False;
Break;
end;
end;
StatusBar.Panels[0].Text :='客戶端 '+Socket.RemoteHost + ' 已經斷開';
end;
//關閉窗口
procere TfrmServerMain.tbCloseClick(Sender: TObject);
begin
Close;
end;
procere TfrmServerMain.FormCreate(Sender: TObject);
begin
sessions := 0;
end;
procere TfrmServerMain.FormClose(Sender: TObject;var Action: TCloseAction);
begin
ServerSocket.Close ;
end;
//當客戶端正在與伺服器端連接時
procere TfrmServerMain.ServerSocketGetSocket(Sender: TObject;
Socket: Integer; var ClientSocket: TServerClientWinSocket);
begin
StatusBar.Panels[0].Text :='客戶端正在連接...';
end;
//客戶端發生錯誤
procere TfrmServerMain.ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
StatusBar.Panels[0].Text :='客戶端'+Socket.RemoteHost +'發生錯誤!';
ErrorCode := 0;
end;
end.

『叄』 linux下socket 網路編程(客戶端向伺服器端發送文件) 求源代碼 大哥大姐幫幫忙 ,。。謝謝

源代碼奉上,流程圖。。。這個太簡單了,你自己看看。。。。。。。

//TCP
//伺服器端程序
#include< stdio.h >
#include< stdlib.h >
#include< windows.h >
#include< winsock.h >
#include< string.h >

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

#define PORT 2046
#define BACKLOG 10
#define TRUE 1

void main( void )
{
int iServerSock;
int iClientSock;

char *buf = "hello, world!\n";

struct sockaddr_in ServerAddr;
struct sockaddr_in ClientAddr;

int sin_size;

WSADATA WSAData;

if( WSAStartup( MAKEWORD( 1, 1 ), &WSAData ) )//初始化
{
printf( "initializationing error!\n" );
WSACleanup( );
exit( 0 );
}

if( ( iServerSock = socket( AF_INET, SOCK_STREAM, 0 ) ) == INVALID_SOCKET )
{
printf( "創建套接字失敗!\n" );
WSACleanup( );
exit( 0 );
}

ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons( PORT );//監視的埠號
ServerAddr.sin_addr.s_addr = INADDR_ANY;//本地IP
memset( & ( ServerAddr.sin_zero ), 0, sizeof( ServerAddr.sin_zero ) );

if( bind( iServerSock, ( struct sockaddr * )&ServerAddr, sizeof( struct sockaddr ) ) == -1 )
{
printf( "bind調用失敗!\n" );
WSACleanup( );
exit( 0 );
}

if( listen( iServerSock, BACKLOG ) == -1 )
{
printf( "listen調用失敗!\n" );
WSACleanup( );
exit( 0 );
}

while( TRUE )
{
sin_size = sizeof( struct sockaddr_in );
iClientSock = accept( iServerSock, ( struct sockaddr * )&ClientAddr, &sin_size );

if( iClientSock == -1 )
{
printf( "accept調用失敗!\n" );
WSACleanup( );
exit( 0 );
}

printf( "伺服器連接到%s\n", inet_ntoa( ClientAddr.sin_addr ) );
if( send( iClientSock, buf, strlen( buf ), 0 ) == -1 )
{
printf( "send調用失敗!" );
closesocket( iClientSock );
WSACleanup( );
exit( 0 );
}
}
}

/////客戶端程序
#include< stdio.h >
#include< stdlib.h >
#include< windows.h >
#include< winsock.h >
#include< string.h >

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

#define PORT 2046
#define BACKLOG 10
#define TRUE 1
#define MAXDATASIZE 100

void main( void )
{

int iClientSock;
char buf[ MAXDATASIZE ];
struct sockaddr_in ServerAddr;
int numbytes;
// struct hostent *he;
WSADATA WSAData;

// int sin_size;

/* if( ( he = gethostbyname( "liuys" ) ) == NULL )
{
printf( "gethostbyname調用失敗!" );
WSACleanup( );
exit( 0 );
}
*/

if( WSAStartup( MAKEWORD( 1, 1 ), &WSAData ) )//初始化
{
printf( "initializationing error!\n" );
WSACleanup( );
exit( 0 );
}

if( ( iClientSock = socket( AF_INET, SOCK_STREAM, 0 ) ) == INVALID_SOCKET )
{
printf( "創建套接字失敗!\n" );
WSACleanup( );
exit( 0 );
}

ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons( PORT );
// ServerAddr.sin_addr = *( ( struct in_addr * )he->h_addr );
ServerAddr.sin_addr.s_addr = inet_addr( "192.168.2.194" );//記得換IP
memset( &( ServerAddr.sin_zero ), 0, sizeof( ServerAddr.sin_zero ) );

if( connect( iClientSock, ( struct sockaddr * ) & ServerAddr, sizeof( struct sockaddr ) ) == -1 )
{
printf( "connect失敗!" );
WSACleanup( );
exit( 0 );
}

numbytes = recv( iClientSock, buf, MAXDATASIZE, 0 );

if( numbytes == -1 )
{
printf( "recv失敗!" );
WSACleanup( );
exit( 0 );
}

buf[ numbytes ] = '\0';

printf( "Received: %s", buf );

closesocket( iClientSock );
WSACleanup( );
}

/////UDP
//伺服器
#include< stdio.h >
#include< string.h >
#include< winsock.h >
#include< windows.h >

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

#define PORT 2046
#define BACKLOG 10
#define TRUE 1
#define MAXDATASIZE 1000

void main( void )
{
int iServerSock;
// int iClientSock;

int addr_len;
int numbytes;

char buf[ MAXDATASIZE ];

struct sockaddr_in ServerAddr;
struct sockaddr_in ClientAddr;

WSADATA WSAData;
if( WSAStartup( MAKEWORD( 1, 1 ), &WSAData ) )
{
printf( "initializationing error!\n" );
WSACleanup( );
exit( 0 );
}

iServerSock = socket( AF_INET, SOCK_DGRAM, 0 );
if( iServerSock == INVALID_SOCKET )
{
printf( "創建套接字失敗!\n" );
WSACleanup( );
exit( 0 );
}

ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons( PORT );//監視的埠號
ServerAddr.sin_addr.s_addr = INADDR_ANY;//本地IP
memset( & ( ServerAddr.sin_zero ), 0, sizeof( ServerAddr.sin_zero ) );

if( bind( iServerSock, ( struct sockaddr * )&ServerAddr, sizeof( struct sockaddr ) ) == -1 )
{
printf( "bind調用失敗!\n" );
WSACleanup( );
exit( 0 );
}

addr_len = sizeof( struct sockaddr );
numbytes = recvfrom( iServerSock, buf, MAXDATASIZE, 0, ( struct sockaddr * ) & ClientAddr, &addr_len );
if( numbytes == -1 )
{
printf( "recvfrom調用失敗!\n" );
WSACleanup( );
exit( 0 );
}

printf( "got packet from %s\n", inet_ntoa( ClientAddr.sin_addr ) );
printf( "packet is %d bytes long\n", numbytes );
buf[ numbytes ] = '\0';
printf( "packet contains \"%s\"\n", buf );

closesocket( iServerSock );
WSACleanup( );

}
//客戶端
#include< stdio.h >
#include< stdlib.h >
#include< windows.h >
#include< winsock.h >
#include< string.h >

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

#define PORT 2046
#define MAXDATASIZE 100

void main( void )
{

int iClientSock;
struct sockaddr_in ServerAddr;

int numbytes;
char buf[ MAXDATASIZE ] = { 0 };

WSADATA WSAData;
if( WSAStartup( MAKEWORD( 1, 1 ), &WSAData ) )
{
printf( "initializationing error!\n" );
WSACleanup( );
exit( 0 );
}

if( ( iClientSock = socket( AF_INET, SOCK_DGRAM, 0 ) ) == -1 )
{
printf( "創建套接字失敗!\n" );
WSACleanup( );
exit( 0 );
}

ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons( PORT );
ServerAddr.sin_addr.s_addr = inet_addr( "192.168.2.194" );//記得換IP
memset( &( ServerAddr.sin_zero ), 0, sizeof( ServerAddr.sin_zero ) );

numbytes = sendto( iClientSock, buf, strlen( buf ), 0, ( struct sockaddr * ) & ServerAddr, sizeof( struct sockaddr ) );
if( numbytes == -1 )
{
printf( "sendto調用失敗!\n" );
WSACleanup( );
exit( 0 );
}

printf( "sent %d bytes to %s\n", numbytes, inet_ntoa( ServerAddr.sin_addr ) );

closesocket( iClientSock );
WSACleanup( );
}

『肆』 linux下socket 網路編程(客戶端向伺服器端發送文件) 求源代碼 大哥大姐幫幫忙 。。謝謝

server:

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <syslog.h>
#include <sys/time.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>

#define MAXDATASIZE 1024
#define SERVPORT 19999
#define BACKLOG 10

int SendFileToServ(const char *path, const char *FileName, const char *ip)
{
#define PORT 20002
int sockfd;
int recvbytes;
char buf[MAXDATASIZE];
char send_str[MAXDATASIZE];
char filepath[128] = {0};
struct sockaddr_in serv_addr;
FILE *fp;
sprintf(filepath, "%s%s", path, FileName);

if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
return 1;
}
bzero(&serv_addr,sizeof(struct sockaddr_in));
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(PORT);
inet_aton(ip, &serv_addr.sin_addr);
int IErrCount = 0;
again:
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1)
{
if (5 == IErrCount)
return 1;
IErrCount++;
perror("connect");
sleep(2);
goto again;
}
//if ((fp = fopen(FileName, "rb")) == NULL)
if ((fp = fopen(filepath, "rb")) == NULL)
{
perror("fopen ");
return 1;
}
recvbytes = write(sockfd, FileName, strlen(FileName));
recvbytes = read(sockfd, buf, MAXDATASIZE);
if (!memcmp(buf, "sendmsg", 7))
{
while(fgets(send_str, MAXDATASIZE, fp))
{
recvbytes = write(sockfd, send_str, strlen(send_str));
recvbytes = read(sockfd, buf, MAXDATASIZE);
if (recvbytes <= 0)
{
fclose(fp);
close(sockfd);
return 1;
}
if (memcmp(buf, "goon", 4))
{
fclose(fp);
close(sockfd);
return 1;
}
}
recvbytes = write(sockfd, "end", 3);
}
else
{
fclose(fp);
close(sockfd);
return 1;
}
memset(buf, 0, MAXDATASIZE);
if (read(sockfd, buf, MAXDATASIZE) <= 0)
{
close(sockfd);
return 2;
}
char *Eptr = "nginx reload error";
//printf("bf[%s]\n", buf);
int ret;
ret = strncmp(buf, Eptr, strlen(Eptr));
//printf("%d\n", ret);
if (!ret)
{
close(sockfd);
return 2;
}

close(sockfd);
return 0;
}

int mysyslog(const char * msg)
{
FILE *fp;
if ((fp = fopen("/tmp/tmp.log", "a+")) == NULL)
{
return 0;
}
fprintf(fp, "[%s]\n", msg);
fclose(fp);
return 0;
}
static void quit_handler(int signal)
{
kill(0, SIGUSR2);
syslog( LOG_NOTICE, "apuserv quit...");
// do something exit thing ,such as close socket ,close mysql,free list
// .....
//i end
exit(0);
}
static int re_conf = 0;
static void reconf_handler(int signal)
{
re_conf=1;
syslog(LOG_NOTICE,"apuserv reload configure file .");
// 請在循環體中判斷,如果re_conf == 1,請再次載入配置文件。
}
static int isrunning(void)
{
int fd;
int ret;
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = 0;
lock.l_start = 0;
lock.l_len = 0;
const char *lckfile = "/tmp/apuserv.lock";
fd = open(lckfile,O_WRONLY|O_CREAT);
if (fd < 0) {
syslog(LOG_ERR,"can not create lock file: %s\n",lckfile);
return 1;
}
if ((ret = fcntl(fd,F_SETLK,&lock)) < 0) {
ret = fcntl(fd,F_GETLK,&lock);
if (lock.l_type != F_UNLCK) {
close(fd);
return lock.l_pid;
}
else {
fcntl(fd,F_SETLK,&lock);
}
}
return 0;
}

int MyHandleBuff(const char *buf, char *str, char *FileName, char *pth)
{
sscanf(buf, "%s %s %s", pth, FileName, str);
printf("path=%s\nfilename=%s\nip=%s\n", pth, FileName, str);
return 0;
}

int main(int argc, char **argv)
{
int sockfd,client_fd;
socklen_t sin_size;
struct sockaddr_in my_addr,remote_addr;
char buff[MAXDATASIZE];
int recvbytes;
#if 1
int pid ;
char ch ;
int ret;
int debug = 0;
signal(SIGUSR1, SIG_IGN);
signal(SIGUSR2, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGTERM, quit_handler);
syslog(LOG_NOTICE,"apuserver start....");
while ((ch = getopt(argc, argv, "dhV")) != -1) {
switch (ch) {
case 'd':
debug = 1;
break;
case 'V':
printf("Version:%s\n","1.0.0");
return 0;
case 'h':
printf(" -d use daemon mode\n");
printf(" -V show version\n");
return 0;
default:
printf(" -d use daemon mode\n");
printf(" -V show version\n");
}
}
if (debug && daemon(0,0 ) ) {
return -1;
}
if (isrunning()) {
fprintf(stderr, "apuserv is already running\n");
syslog(LOG_INFO,"apuserv is already running\n");
exit(0);
}
while (1) {
pid = fork();
if (pid < 0)
return -1;
if (pid == 0)
break;
while ((ret = waitpid(pid, NULL, 0)) != pid) {
syslog(LOG_NOTICE, "waitpid want %d, but got %d", pid, ret);
if (ret < 0)
syslog(LOG_NOTICE, "waitpid errno:%d", errno);
}
kill(0, SIGUSR2);
sleep(1);
syslog(LOG_NOTICE,"restart apuserver");
}
signal(SIGHUP, reconf_handler);
signal(SIGPIPE, SIG_IGN);
signal(SIGUSR1,SIG_IGN);
signal(SIGUSR2, SIG_DFL);
signal(SIGTERM, SIG_DFL);
#endif
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}

bzero(&my_addr,sizeof(struct sockaddr_in));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(1);
}
if(listen(sockfd,BACKLOG)==-1)
{
perror("listen");
exit(1);
}
int nret;
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size))==-1)
{
perror("falied accept");
continue;
}
memset(buff, 0, MAXDATASIZE);
recvbytes = read(client_fd, buff, MAXDATASIZE);
char str[16] = {0};
char FileName[128] = {0};
char path[128] = {0};
MyHandleBuff(buff, str, FileName, path);
if (recvbytes > 0)
{
nret = SendFileToServ(path, FileName, str);
printf("nret[%d]\n", nret);
if (1 == nret)
write(client_fd, "send file error", 15);
else if(2 == nret)
write(client_fd, "reload nginx error", 18);
else
write(client_fd, "succ", 4);
}
close(client_fd);
}
}
_________________________________________________
client:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <syslog.h>
#include <sys/time.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>

#define MAXDATASIZE 1024
#define SERVPORT 20002
#define BACKLOG 10

int mysyslog(const char * msg)
{
FILE *fp;
if ((fp = fopen("/tmp/tmp.log", "a+")) == NULL)
{
return 0;
}
fprintf(fp, "[%s]\n", msg);
fclose(fp);
return 0;
}
static void quit_handler(int signal)
{
kill(0, SIGUSR2);
syslog( LOG_NOTICE, "apuserv quit...");
// do something exit thing ,such as close socket ,close mysql,free list
// .....
//i end
exit(0);
}
static int re_conf = 0;
static void reconf_handler(int signal)
{
re_conf=1;
syslog(LOG_NOTICE,"apuserv reload configure file .");
// ????·???????1nf == 1£???′μ?????

static int isrunning(void)
{
int fd;
int ret;
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = 0;
lock.l_start = 0;
lock.l_len = 0;
const char *lckfile = "/tmp/dstserver.lock";
fd = open(lckfile,O_WRONLY|O_CREAT);
if (fd < 0) {
syslog(LOG_ERR,"can not create lock file: %s\n",lckfile);
return 1;
}
if ((ret = fcntl(fd,F_SETLK,&lock)) < 0) {
ret = fcntl(fd,F_GETLK,&lock);
if (lock.l_type != F_UNLCK) {
close(fd);
return lock.l_pid;
}
else {
fcntl(fd,F_SETLK,&lock);
}
}
return 0;
}

int main(int argc, char **argv)
{
int sockfd,client_fd;
socklen_t sin_size;
struct sockaddr_in my_addr,remote_addr;
char buff[MAXDATASIZE];
int recvbytes;
#if 1
int pid ;
char ch ;
int ret;
int debug = 0;
signal(SIGUSR1, SIG_IGN);
signal(SIGUSR2, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGTERM, quit_handler);
syslog(LOG_NOTICE,"dstserver start....");

while ((ch = getopt(argc, argv, "dhV")) != -1) {
switch (ch) {
case 'd':
debug = 1;
break;
case 'V':
printf("Version:%s\n","1.0.0");
return 0;
case 'h':
printf(" -d use daemon mode\n");
printf(" -V show version\n");
return 0;
default:
printf(" -d use daemon mode\n");
printf(" -V show version\n");
}
}
if (debug && daemon(0,0 ) ) {
return -1;
}
if (isrunning()) {
fprintf(stderr, "dstserver is already running\n");
syslog(LOG_INFO,"dstserver is already running\n");
exit(0);
}
while (1) {
pid = fork();
if (pid < 0)
return -1;
if (pid == 0)
break;
while ((ret = waitpid(pid, NULL, 0)) != pid) {
syslog(LOG_NOTICE, "waitpid want %d, but got %d", pid, ret);
if (ret < 0)
syslog(LOG_NOTICE, "waitpid errno:%d", errno);
}
kill(0, SIGUSR2);
sleep(1);
syslog(LOG_NOTICE,"restart apuserver");
}
signal(SIGHUP, reconf_handler);
signal(SIGPIPE, SIG_IGN);
signal(SIGUSR1,SIG_IGN);
signal(SIGUSR2, SIG_DFL);
signal(SIGTERM, SIG_DFL);
#endif
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}

bzero(&my_addr,sizeof(struct sockaddr_in));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(1);
}
if(listen(sockfd,BACKLOG)==-1)
{
perror("listen");
exit(1);
}

char filepath[MAXDATASIZE]= {0};
FILE *fp;
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size))==-1)
{
perror("falied accept");
continue;
}
memset(buff, 0, MAXDATASIZE);
recvbytes = read(client_fd, buff, MAXDATASIZE);
sprintf(filepath, "/etc/nginx/url_rule/%s", buff);
if ((fp = fopen(filepath, "wb")) == NULL)
{
perror("fopen");
close(client_fd);
continue;
}
write(client_fd, "sendmsg", 7);
while(read(client_fd, buff, MAXDATASIZE))
{
if (!memcmp(buff, "end", 3))
{
fclose(fp);
break;
}
else
{
fprintf(fp, "%s", buff);
write(client_fd, "goon", 4);
}
}
//system("nginx -s reload");
char *Sptr = "nginx reload succ";
char *Eptr = "nginx reload error";
int ret;
ret = system("nginx -s reload");
printf("ret[%d]\n", ret);
if (ret != 0)
{
write(client_fd, Eptr, strlen(Eptr));
}
else
{
write(client_fd, Sptr, strlen(Sptr));
}
close(client_fd);
}
}

以前寫的:內容忘記了。不是很復雜你可以自己看!

閱讀全文

與socket程序源碼相關的資料

熱點內容
冬天程序員面試穿搭女生 瀏覽:421
開會時如何發言app 瀏覽:941
手寫加密演算法java版 瀏覽:43
如何使用命令解壓rar 瀏覽:832
海爾之家app怎麼連接設備 瀏覽:854
高壓水槍壓槍解壓視頻 瀏覽:776
如何檢索遠程伺服器的ip地址 瀏覽:26
華為西安演算法中心 瀏覽:785
安卓什麼app的組件好看 瀏覽:550
外網伺服器地址誰有 瀏覽:192
計算三角形面積java 瀏覽:676
如何24小時開伺服器 瀏覽:726
靈動單片機的模擬設置 瀏覽:790
重慶監控伺服器雲主機 瀏覽:254
python環境模塊安裝 瀏覽:217
梧桐木和壓縮板的桌子哪個好 瀏覽:43
單片機註解 瀏覽:572
怎麼樣讓安卓系統更流暢 瀏覽:992
php抓取網頁圖片 瀏覽:80
重生伺服器是什麼 瀏覽:290