TCP客戶端代碼
#include<myhead.h>
#define SER_IP "192.168.108.179" ? ?//服務器ip地址
#define SER_PORT 8888 ? ? ? ? ? ? ? //服務器端口號
#define CLI_IP "192.168.108.239" ? ? //客戶端ip地址
#define CLI_PORT 7777 ? ? ? ? ? ? ? //客戶端端口號
//TCP客戶端
int main(int argc, const char *argv[])
{
//創建用于通信的套接字文件描述符
int cfd = socket(AF_INET, SOCK_STREAM, 0);
if(cfd == -1)
{
perror("socket error");
return -1;
}
?? ?//連接服務器
//服務器地址信息結構體
struct sockaddr_in sin;
sin.sin_family = AF_INET; ? ?//IPV4
sin.sin_addr.s_addr = inet_addr(SER_IP);//要連接的服務器IP
sin.sin_port = htons(SER_PORT); ? ? //服務器的端口號
????//連接操作
if(connect(cfd, (struct sockaddr*)&sin, sizeof(sin))==-1)
{
perror("connect error");
return -1;
}
//紅色臂初始角度
char rbuf[5] = {0xff, 0x02, 0x00, 0x00, 0xff};
//藍色臂初始角度
unsigned char bbuf[5] = {0xff, 0x02, 0x01, 0x5a, 0xff};
?? ?//將上面的數據分別發送給服務器
send(cfd, rbuf, sizeof(rbuf), 0);
send(cfd, bbuf, sizeof(bbuf), 0);
?? ?//WASD功能
char input;
while(1)
{
scanf("? %c",&input);
switch(input)
{
case 'w':
rbuf[3]+=2;
send(cfd,rbuf,sizeof(rbuf),0);
break;
case 's':
rbuf[3]-=2;
send(cfd,rbuf,sizeof(rbuf),0);
break;
case 'd':
bbuf[3]+=2;
send(cfd,bbuf,sizeof(bbuf),0);
break;
case 'a':
bbuf[3]-=2;
send(cfd,bbuf,sizeof(bbuf),0);
break;
case 'q':
printf("退出\n");
close(cfd);
return 0;
default:
break;
}
}
//關閉套接字
close(cfd);
return 0;
}