SOCKET网络编程考级(Socket网络编程)

2024-01-05 10:59:06 数码极客 bianji01

 

socket接口网络编程

面向无连接的端对端通信

//#iNclude

//#pragmacomment(lib,"WS2_32.lib")

WSADATAwsd;

SOCKETs;

charbuf[1024];

if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)

return-1;//失败

s=socket(AF_INET,SOCK_DGRAM,0);

if(s==INVALID_SOCKET)

WSACleanup();

return-1;//创建套接字失败

SOCKADDR_INservAddr;

servAddr.sin_family=AF_INET;

servAddr.sin_addr.s_addr=inet_addr(%%1);

servAddr.sin_port=htons(INADDR_ANY);

if(bind(s,(SOCKADDR*)&servAddr,sizeof(SOCKADDR_IN))==SOCKET_ERROR)

closesocket(s);

WSACleanup();

return-1;//绑定套接字失败

intnServAddrlen=sizeof(servAddr);

ZeroMemory(buf,sizeof(buf));

if(recvfrom(s,buf,size(buf),0,(SOCKADDR*)&servAddr,nServAddrlen)==SOCKET_ERROR)

closesocket(s);

WSACleanup();

return-1;//接收数据失败

CString%%2(buf);

ZeroMemory(buf,sizeof(buf));

strcpy(buf,%%3);

SOCKADDR_INclientAddr;

clientAddr.sin_family=AF_INET;

clientAddr.sin_addr.s_addr=inet_addr(%%4);

clientAddr.sin_port=htons((short)%%5);

intnClientlen=size(clientAddr);

if(sendto(s,buf,sizeof(buf),0,(SOCKADDR*)&clientAddr,nClientlen)==SOCKET_ERROR)

closesocket(s);

WSACleanup();

return-1;//向服务器发送数据失败

closesocket(s);

WSACleanup();

网络编程 socket

这个语言很怪,不像c语言,哎,我也不晓得没有对recvbuf做清空设置啊。char recvbuf[100];memset(recvbuf, 0x00, 100);recv(stockcon,recvbuf,100,0);printf("%s\n",recvbuf);closesocket(stockcon);

socket接口网络编程

服务器 package test; import java.net.*; import java.io.*; public class kkmultiserver { private socket socket=nuLL; private serversocket ss; string ip="192.168.1.182"; int port =8001; thread trd=null; public void start() { try { ss=new serversocket(port,20,inetaddress.getbyname(ip)); system.out.println("服务器建立等待用户连接!"); while(true) { socket=ss.accept(); system.out.println("用户连接成功"); trd=new thread(new guestserver(socket)); trd.start(); } } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } public static void main(string args[]) { new kkmultiserver().start(); } }

socket网络编程

服务器与每一个客户端建立连接,就多了一个线程,通过对线程的名字和Socket对象来进行处理,保存到hasmap.写一个遍历hasmap可以得到每个客服的Socket,这样就可以发送到各个客服端了!

声明:易趣百科所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系315127732@qq.com
广告位招租
横幅广告