时间:2021-05-19
功能简单实现client输入内容发送到server端输出
复制代码 代码如下:
#include <stdio.h>
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
// 初始化 Winsock.
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ( iResult != NO_ERROR )
{
cout<<"failed to initialize!"<<endl;
return 0;
}
// 建立socket socket.
SOCKET client;
client = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( client == INVALID_SOCKET )
{
cout<<"failed to create client socket!"<<endl;
WSACleanup();
return 0;
}
// 连接到服务器.
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
clientService.sin_port = htons( 13579 );
if ( connect( client, (SOCKADDR*) &clientService, sizeof(clientService) ) == SOCKET_ERROR)
{
cout<<"Failed to connect"<<endl;
closesocket(client);
WSACleanup();
return 0;
}
// 发送数据.
int bytesSent;
char sendbuf[4096] = "Client: Sending data.";
while(TRUE)
{
bytesSent = send( client, sendbuf, strlen(sendbuf), 0 );
gets_s(sendbuf, 4096);
}
closesocket(client);
WSACleanup();
return 0;
}
复制代码 代码如下:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
WSADATA wsaData;
int iInit = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iInit != NO_ERROR)
{
cout<<"failed to initialize!"<<endl;
return 0;
}
SOCKET server = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server == INVALID_SOCKET)
{
cout<<"failed to create server socket!"<<endl;
WSACleanup();
return 0;
}
sockaddr_in bindinfo;
bindinfo.sin_family = AF_INET;
bindinfo.sin_addr.s_addr = inet_addr( "127.0.0.1" );
bindinfo.sin_port = htons(13579);
if ( bind( server, (SOCKADDR*) &bindinfo, sizeof(bindinfo) ) == SOCKET_ERROR )
{
cout<<"failed to bind!"<<endl;
closesocket(server);
WSACleanup();
return 0;
}
//listen
if (listen(server, 1) == SOCKET_ERROR) {
cout<<"listen failed"<<endl;
closesocket(server);
WSACleanup();
return 0;
}
//accept and block
SOCKET socketWork = accept(server, NULL, NULL);
if (socketWork == INVALID_SOCKET) {
wprintf(L"accept failed with error: %ld\n", WSAGetLastError());
closesocket(server);
WSACleanup();
return 0;
}
int byteRecv = SOCKET_ERROR;
char recvBuf[4096] = "";
while(TRUE)
{
byteRecv = recv(socketWork, recvBuf, 4096, 0);
if (byteRecv == 0)
{
break;
}
recvBuf[byteRecv] = 0;
cout<<recvBuf<<endl;
}
closesocket(server);
WSACleanup();
return 0;
}
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
这篇文章将向大家展示Java编程利用socket多线程访问服务器文件代码示例,如果您想先了解Java多线程socket编程的基础知识,可以看下这篇文章:Java
这是用来快速学习PythonSocket套接字编程的指南和教程。Python的Socket编程跟C语言很像。Python官方关于Socket的函数请看http:
本文实例讲述了android开发socket编程之udp发送实现方法。分享给大家供大家参考。具体分析如下:需要实现的功能:采用udp下的socket编程,当按下
Freemarker入门示例FreeMarker整合Struts2示例SiteMesh入门示例那么如何将Freemarker与SiteMesh结合起来使用,这在
一、UDP编程1.客户端Client:发起访问的一方。2.服务器端3.server段编程(1)建立socket,socket是负责具体通信的一个实例(2)绑定,