3
服务器端代码发送数据多次:过于单一插座
static void Main(string[] args)
{
static Socket sck;
Console.WriteLine("Server Started...");
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(0, 1234));
while (true)
{
sck.Listen(100);
Socket accepted = sck.Accept();
buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
formatted[i] = buffer[i];
string strdata = Encoding.ASCII.GetString(formatted);
Console.WriteLine(strdata + "\r");
// sck.Close();
}
客户端代码:
static void Main(string[] args)
{
static Socket sck;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
try
{
sck.Connect(localEndpt);
}
catch
{
Console.Write("Unable to Connect");
}
while (true)
{
Console.WriteLine("Enter Text");
string sendtext = Console.ReadLine();
byte[] Data = Encoding.ASCII.GetBytes(sendtext);
sck.Send(Data);
Console.WriteLine("Data Sent!");
//sck.Close();
//Console.Read();
}
我想从客户端发送文本多次,但文本发送只有第一次。请告诉我我哪里错了。
我在循环前移动了listen语句,但仍然面临同样的问题 – Tempo 2012-02-23 03:09:01
正如我所说的,您需要移动您的接收语句循环。您应该接受一次但尚未收到多次的客户 – Polity 2012-02-23 03:14:13