gpt4 book ai didi

C#如何用客户端向服务器发送更多消息?

转载 作者:可可西里 更新时间:2023-11-01 02:53:27 24 4
gpt4 key购买 nike

我正在使用 TCP 协议(protocol)编写客户端服务器套接字 C# 以创建某种“客户端询问,服务器回答”但是当我执行第一个命令时,我的客户端关闭。我应该把 while 放在某个地方,但我不知道放在哪里。这是代码:

客户

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketClient
{

public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];

// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());

Console.WriteLine("Insert text to send to server");
String a = Console.ReadLine(); //This is a test<EOF>
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(a);

// Send the data through the socket.
int bytesSent = sender.Send(msg);

// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));

// Release the socket.
//sender.Shutdown(SocketShutdown.Both);
//sender.Close();

}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

public static int Main(String[] args)
{
StartClient();
//To avoid Prompt disappear
Console.Read();
return 0;
}

服务器

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;

public class SynchronousSocketListener
{

// Incoming data from the client.
public static string data = null;

public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);

byte[] msg = null;
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;

// An incoming connection needs to be processed.
while (true)
{


bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

if (data.Equals("ping"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);

// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes("pong");
handler.Send(msg);
break;
}
if (data.Equals("dir"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);

// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
handler.Send(msg);
break;
}

if (data.Equals("files"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);

String files = "";

string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
foreach (string fileName in fileEntries)
files += ProcessFile(fileName);

// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(files);
handler.Send(msg);
break;
}
}

// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);

// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);

//handler.Send(msg);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Console.WriteLine("\nPress ENTER to continue...");
Console.Read();

}

public static String ProcessFile(string path)
{
return path += "\n\n" + path;
}

public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(fileName);

// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}

public static int Main(String[] args)
{
StartListening();
return 0;
}

现在,如果您复制粘贴此代码并执行服务器,然后执行客户端,您可以在客户端提示符下写入一些内容并获得答案,但在第 2 次尝试关闭客户端时,因为没有 while 继续该过程!我试过 put 而不是 try 和 into 但代码崩溃了!帮助将不胜感激帮助或解决方案是相同的,只需得到答案:)谢谢大家

最佳答案

我对套接字的了解有限。但是我知道你应该只调用以下一次:

Socket handler = listener.Accept();

我在上面的行下面添加了一个 while 循环,还删除了 if 条件末尾的 break 语句。

所以新的代码变成了:

客户

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketClient
{

public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];

// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{

sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());

while (true)
{

Console.WriteLine("Insert text to send to server");
String a = Console.ReadLine(); //This is a test<EOF>
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(a);

// Send the data through the socket.
int bytesSent = sender.Send(msg);

// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));

}
// Release the socket.
//sender.Shutdown(SocketShutdown.Both);
//sender.Close();

}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

public static int Main(String[] args)
{
StartClient();
//To avoid Prompt disappear
Console.Read();
return 0;
}
}

服务器

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;

public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;

public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

// Bind the socket to the local endpoint and
// listen for incoming connections.
while (true)
{


try
{
//if (!listener.IsBound)
//{
listener.Bind(localEndPoint);
//}
listener.Listen(10);

byte[] msg = null;
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
while (true)
{


data = null;

// An incoming connection needs to be processed.
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

if (data.Equals("ping"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);

// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes("pong");
handler.Send(msg);
//break;
}
if (data.Equals("dir"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);

// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
handler.Send(msg);
//break;
}

if (data.Equals("files"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);

String files = "";

string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
foreach (string fileName in fileEntries)
files += ProcessFile(fileName);

// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(files);
handler.Send(msg);
//break;

}
}

// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);

// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);

//handler.Send(msg);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}

}

catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();

}

public static String ProcessFile(string path)
{
return path += "\n\n" + path;
}

public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(fileName);

// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}

public static int Main(String[] args)
{
StartListening();
return 0;
}
}

关于C#如何用客户端向服务器发送更多消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46676804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com