如何解决无法使用C#套接字接收字节
我正在尝试制作一个简单的聊天服务器。服务器接受来自客户端的连接,但不接收任何字节,我对C#和OOP还是很陌生,因此这可能与套接字完全无关,仅在我的代码中,我尝试查看以下示例使用c#进行套接字连接,但由于缺乏知识,我无法在程序中实现它。
//server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketLogger
{
class Program
{
static void Main(string[] args)
{
startServer();
}
public static void startServer()
{
IPAddress IPaddr = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener listener = new TcpListener(IPaddr,6969);
TcpClient client = default(TcpClient);
try
{
listener.Start();
Console.WriteLine("Server Has Started");
}
catch(Exception err)
{
Console.WriteLine("error:" + err);
}
while(true)
{
listener.AcceptTcpClient();
Console.WriteLine("Accepted Client");
byte[] buffer = new byte[1024];
client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
stream.Read(buffer,buffer.Length);
string message = Encoding.ASCII.GetString(buffer,buffer.Length);
Console.WriteLine(message);
Console.Read();
}
}
}
}
//client
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ClientConnect
{
class Program
{
static void Main(string[] args)
{
startClientConnection();
}
public static void startClientConnection()
{
string testString = "hello";
TcpClient client = new TcpClient("127.0.0.1",6969);
//the teststring is for testing purposes
int SentBytes = Encoding.ASCII.GetByteCount(testString);
byte[] sendBuffer = new byte[SentBytes];
sendBuffer = Encoding.ASCII.GetBytes(testString);
NetworkStream stream = client.GetStream();
stream.Write(sendBuffer,sendBuffer.Length);
stream.Close();
client.Close();
Console.Read();
}
}
}
解决方法
为了在我的机器上测试您的代码,我不得不更改向服务器提供IPAddress的方式。这个:
IPAddress IPaddr = Dns.GetHostEntry("localhost").AddressList[0];
为IPaddr设置一个IPv6地址。而这,在客户端代码上:
TcpClient client = new TcpClient("127.0.0.1",6969);
为客户端提供一个IPv4地址。因此,我将服务器代码更改为:
// IPAddress IPaddr = Dns.GetHostEntry("localhost").AddressList[0];
IPAddress IPaddr = IPAddress.Parse("127.0.0.1");
继续进行下一个问题,因为执行两个AcceptTcpClient(),服务器丢失了客户端字节。将代码更改为:
//listener.AcceptTcpClient();
byte[] buffer = new byte[1024];
client = listener.AcceptTcpClient();
Console.WriteLine("Accepted Client");
它将接收字符串。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。