客户端与服务器端的通讯,C++书写步骤。

客户端与服务器端的通讯,C++书写步骤。,第1张

要实现客户端服务器端的通讯,需要两部分C++的程序:服务器端程序代码和客户端代码。

首先是服务器端程序代码:

#include <WinSock2.h>

#include <stdio.h>

#include <stdlib.h> 

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

void main()

{

WSADATA wsaData

int port = 5099

char buf[] = "Server: hello, I am a server....."

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

{

printf("Failed to load Winsock")

return

//创建用于监听的套接字

SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0)

SOCKADDR_IN addrSrv

addrSrv.sin_family = AF_INET

addrSrv.sin_port = htons(port)//1024以上的端口号

addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY)

int retVal = bind(sockSrv, (LPSOCKADDR)&addrSrv, sizeof(SOCKADDR_IN))

if(retVal == SOCKET_ERROR){

printf("Failed bind:%d\n", WSAGetLastError())

return

}

if(listen(sockSrv,10) ==SOCKET_ERROR){

printf("Listen failed:%d", WSAGetLastError())

return

}

SOCKADDR_IN addrClient

int len = sizeof(SOCKADDR)

while(1)

{

//等待客户请求到来

SOCKET sockConn = accept(sockSrv, (SOCKADDR *) &addrClient, &len)

if(sockConn == SOCKET_ERROR){

printf("Accept failed:%d", WSAGetLastError())

break

}

printf("Accept client IP:[%s]\n", inet_ntoa(addrClient.sin_addr))

//发送数据

int iSend = send(sockConn, buf, sizeof(buf) , 0)

if(iSend == SOCKET_ERROR){

printf("send failed")

break

}

char recvBuf[100]

memset(recvBuf, 0, sizeof(recvBuf))

//      //接收数据

recv(sockConn, recvBuf, sizeof(recvBuf), 0)

printf("%s\n", recvBuf)

closesocket(sockConn)

}

closesocket(sockSrv)

WSACleanup()

system("pause")

}

接下来是客户端代码:

#include <WinSock2.h> 

#include <stdio.h>

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

void main()

{

//加载套接字

WSADATA wsaData

char buff[1024]

memset(buff, 0, sizeof(buff))

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

{

printf("Failed to load Winsock")

return

}

SOCKADDR_IN addrSrv

addrSrv.sin_family = AF_INET

addrSrv.sin_port = htons(5099)

addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1")

//创建套接字

SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0)

if(SOCKET_ERROR == sockClient){

printf("Socket() error:%d", WSAGetLastError())

return

}

//向服务器发出连接请求

if(connect(sockClient, (struct  sockaddr*)&addrSrv, sizeof(addrSrv)) == INVALID_SOCKET){

printf("Connect failed:%d", WSAGetLastError())

return

}else

{

//接收数据

recv(sockClient, buff, sizeof(buff), 0)

printf("%s\n", buff)

}

//发送数据

char buff = "hello, this is a Client...."

send(sockClient, buff, sizeof(buff), 0)

//关闭套接字

closesocket(sockClient)

WSACleanup()

}

以前写的,照贴了。。。服务器端:import java.awt.*\x0d\x0aimport java.awt.event.WindowAdapter\x0d\x0aimport java.awt.event.WindowEvent\x0d\x0aimport java.io.*\x0d\x0aimport java.net.*/*6、 采用UDP协议,编写一个Java网络应用程序,该应用分服务器端程序和客户端程序两部分。\x0d\x0a* 客户端指定一个服务器上的文件名,让服务器发回该文件的内容,或者提示文件不存在。\x0d\x0a* (20分)(服务端程序和客户端程序分别命名为Server.java和Client.java)*/\x0d\x0apublic class N4BT6 extends Frame\x0d\x0a{\x0d\x0aDatagramSocket socket \x0d\x0aDatagramPacket packet byte[] buf \x0d\x0aFile file \x0d\x0aFileInputStream input\x0d\x0aString message = "该文件不存在"\x0d\x0aTextArea text\x0d\x0apublic N4BT6(String title)\x0d\x0a{\x0d\x0asuper(title)\x0d\x0atext = new TextArea(6,4)\x0d\x0aadd(text)\x0d\x0asetSize(400, 300)\x0d\x0asetVisible(true)\x0d\x0aaddWindowListener(new WindowAdapter()\x0d\x0a{\x0d\x0apublic void windowClosing(WindowEvent e)\x0d\x0a{\x0d\x0adispose()\x0d\x0a}\x0d\x0a})\x0d\x0a\x0d\x0abuf = new byte[1024]\x0d\x0atry\x0d\x0a{\x0d\x0asocket = new DatagramSocket(1230)\x0d\x0apacket = new DatagramPacket(buf, buf.length)\x0d\x0asocket.receive(packet)\x0d\x0afile = new File(new String(packet.getData()))\x0d\x0asocket = new DatagramSocket()\x0d\x0a} \x0d\x0acatch (Exception e)\x0d\x0a{e.printStackTrace()\x0d\x0a}\x0d\x0a\x0d\x0aif(file.exists())\x0d\x0a{\x0d\x0atry\x0d\x0a{\x0d\x0abuf = new byte[(int)file.length()]\x0d\x0apacket = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1234)\x0d\x0ainput = new FileInputStream(file)\x0d\x0ainput.read(buf)\x0d\x0asocket.send(packet)\x0d\x0a}\x0d\x0acatch (IOException e) \x0d\x0a{\x0d\x0ae.printStackTrace()\x0d\x0a}\x0d\x0a}\x0d\x0aelse\x0d\x0a{\x0d\x0atry\x0d\x0a{\x0d\x0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,\x0d\x0aInetAddress.getLocalHost(),1234)\x0d\x0asocket.send(packet)\x0d\x0a}\x0d\x0acatch (Exception e) \x0d\x0a{\x0d\x0ae.printStackTrace()\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0a}\x0d\x0apublic static void main(String[] args)\x0d\x0a{\x0d\x0anew N4BT6("Server")\x0d\x0a}\x0d\x0a}\x0d\x0a客户端:import java.awt.*\x0d\x0aimport java.awt.event.*\x0d\x0aimport java.net.DatagramPacket\x0d\x0aimport java.net.DatagramSocket\x0d\x0aimport java.net.InetAddresspublic class N4BT6_2 extends Frame\x0d\x0a{\x0d\x0aTextArea text\x0d\x0aString message = "Q.txt"\x0d\x0aDatagramSocket socket \x0d\x0aDatagramPacket packet\x0d\x0abyte[] buf\x0d\x0apublic N4BT6_2(String title)\x0d\x0a{\x0d\x0asuper(title)\x0d\x0atext = new TextArea(6,4)\x0d\x0aadd(text)\x0d\x0asetSize(400, 300)\x0d\x0asetVisible(true)\x0d\x0aaddWindowListener(new WindowAdapter()\x0d\x0a{\x0d\x0apublic void windowClosing(WindowEvent e)\x0d\x0a{\x0d\x0adispose()\x0d\x0a}\x0d\x0a})\x0d\x0atry\x0d\x0a{\x0d\x0a\x0d\x0asocket = new DatagramSocket()\x0d\x0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,\x0d\x0aInetAddress.getLocalHost(),1230)\x0d\x0asocket.send(packet)\x0d\x0a}\x0d\x0acatch (Exception e) \x0d\x0a{\x0d\x0ae.printStackTrace()\x0d\x0a}\x0d\x0a\x0d\x0atry\x0d\x0a{\x0d\x0abuf = new byte[1024]\x0d\x0asocket = new DatagramSocket(1234)\x0d\x0apacket = new DatagramPacket(buf,buf.length)\x0d\x0asocket.receive(packet)\x0d\x0atext.append(new String(buf))\x0d\x0a}\x0d\x0acatch (Exception e) \x0d\x0a{\x0d\x0ae.printStackTrace()\x0d\x0a}\x0d\x0a}\x0d\x0apublic static void main(String[] args)\x0d\x0a{\x0d\x0anew N4BT6_2("Client")\x0d\x0a}\x0d\x0a}

先发服务端的(Server)完整代码如下:

引入命名空间:

[csharp] view plain copy print?

using System.Net.Sockets

using System.Net

using System.Threading

完整代码如下:

[csharp] view plain copy print?

namespace SocketServer

{

class Program

{

private static byte[] result = new byte[1024]

private static int myProt = 8885 //端口

static Socket serverSocket

static void Main(string[] args)

{

//服务器IP地址

IPAddress ip = IPAddress.Parse("127.0.0.1")

serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

serverSocket.Bind(new IPEndPoint(ip, myProt)) //绑定IP地址:端口

serverSocket.Listen(10) //设定最多10个排队连接请求

Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString())

//通过Clientsoket发送数据

Thread myThread = new Thread(ListenClientConnect)

myThread.Start()

Console.ReadLine()

}

/// <summary>

/// 监听客户端连接

/// </summary>

private static void ListenClientConnect()

{

while (true)

{

Socket clientSocket = serverSocket.Accept()

clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"))

Thread receiveThread = new Thread(ReceiveMessage)

receiveThread.Start(clientSocket)

}

}

/// <summary>

/// 接收消息

/// </summary>

/// <param name="clientSocket"></param>

private static void ReceiveMessage(object clientSocket)

{

Socket myClientSocket = (Socket)clientSocket

while (true)

{

try

{

//通过clientSocket接收数据

int receiveNumber = myClientSocket.Receive(result)

Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber))

}

catch(Exception ex)

{

Console.WriteLine(ex.Message)

myClientSocket.Shutdown(SocketShutdown.Both)

myClientSocket.Close()

break

}

}

}

}

}

以上是服务端(server)的完整代码。

客户端(Client)的完整代码如下:

引入命名空间:

[csharp] view plain copy print?

using System.Net

using System.Net.Sockets

using System.Threading

完整代码:

[csharp] view plain copy print?

namespace SocketClient

{

class Program

{

private static byte[] result = new byte[1024]

static void Main(string[] args)

{

//设定服务器IP地址

IPAddress ip = IPAddress.Parse("127.0.0.1")

Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

try

{

clientSocket.Connect(new IPEndPoint(ip, 8885))//配置服务器IP与端口

Console.WriteLine("连接服务器成功")

}

catch

{

Console.WriteLine("连接服务器失败,请按回车键退出!")

return

}

//通过clientSocket接收数据

int receiveLength = clientSocket.Receive(result)

Console.WriteLine("接收服务器消息:{0}",Encoding.ASCII.GetString(result,0,receiveLength))

//通过 clientSocket 发送数据

for (int i = 0i <10i++)

{

try

{

Thread.Sleep(1000) //等待1秒钟

string sendMessage = "client send Message Hellp" + DateTime.Now

clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage))

Console.WriteLine("向服务器发送消息:{0}" + sendMessage)

}

catch

{

clientSocket.Shutdown(SocketShutdown.Both)

clientSocket.Close()

break

}

}

Console.WriteLine("发送完毕,按回车键退出")

Console.ReadLine()

}

}

}

编译成功后,先运行 服务端(server),再运行客户端(client)即可达到通信效果。

效果如下图:

该程序已在局域网测试通过。(192.168.X.X)


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/227909.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-08
下一篇2023-04-08

发表评论

登录后才能评论

评论列表(0条)

    保存