用C++建立客户端Socket,怎么用C#建立服务器端Socket进行通信,C++发数据,C#收数据。请给出示例代码。
TcpListener进行监听就可以了。
using System;
using SystemIO;
using SystemNet;
using SystemNetSockets;
using SystemText;
class MyTcpListener
{
public static void Main()
{
TcpListener server=null;
try
{
// Set the TcpListener on port 13000
Int32 port = 8000;
IPAddress localAddr = IPAddressParse("127001");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests
serverStart();
// Buffer for reading data
Byte[] bytes = new Byte[4096];
String data = null;
// Enter the listening loop
while(true)
{
ConsoleWrite("Waiting for a connection ");
// Perform a blocking call to accept requests
// You could also user serverAcceptSocket() here
TcpClient client = serverAcceptTcpClient();
ConsoleWriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = clientGetStream();
int i;
// Loop to receive all the data sent by the client
while((i = streamRead(bytes, 0, bytesLength))!=0)
{
// Translate data bytes to a ASCII string
data = SystemTextEncodingASCIIGetString(bytes, 0, i);
ConsoleWriteLine("Received: {0}", data);
// Process the data sent by the client
data = dataToUpper();
byte[] msg = SystemTextEncodingASCIIGetBytes(data);
// Send back a response
streamWrite(msg, 0, msgLength);
ConsoleWriteLine("Sent: {0}", data);
}
// Shutdown and end connection
clientClose();
}
}
catch(SocketException e)
{
ConsoleWriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients
serverStop();
}
ConsoleWriteLine("\nHit enter to continue");
ConsoleRead();
}
}
当然,官方的这个示例是单线程的,一次只能处理一个客户端,你可以将accept到的client扔到一个独立的线程,这样就可以多客户端并发处理了。
time_t t;
struct tm ti;
char buffer[1048], input[1024];
time(&t); //获取时间戳
ti = localtime(&t); //转成详细时间信息
//格式化时间字符串
sprintf(buffer, "%04d/%02d/%02d %02d:%02d:%02d ",
ti->tm_year + 1900,
ti->tm_mon + 1,
ti->tm_mday,
ti->tm_hour,
ti->tm_min,
ti->tm_sec);
fgets(input, 1024, stdin);
strcat(buffer, input); //连接两个字符串
printf("%s", buffer);
send(sockfd,buffer,strlen(buffer),0);
//望采纳
1、可以在client端登入时write(发送)帐号和密码给server端,当server端接受到内容时判断是否是你预设的帐号密码,是则允许下载,否则关闭其socket。
2、是要客户端看到进度条? 这样就要要求在下载文件时server端要先发这个文件的大小给client端,client端就可以通过这个大小和接受到的字节数比较后打印进度条(printf("#");)
文件大小可用int stat(const char restrict path, struct stat restrict buf);函数获取。
网站模板库 » 用C++建立客户端Socket,怎么用C#建立服务器端Socket进行通信,C++发数据,C#收数据。请给出示例代码。
0条评论