如何能够继续从客户端发送到服务器,而不遵循顺序和冻结
本文关键字:顺序 冻结 服务器 继续 何能够 客户端 | 更新日期: 2023-09-27 18:03:52
我目前正在做一个服务器与客户端之间聊天的应用程序。它可以工作,但它只能遵循由[客户端发送到服务器]->[服务器再次发送到客户端]开始的顺序。如果服务器没有将其发送回客户端,客户端将保持冻结状态。实际上,我想让我的客户端能够在没有这些序列的情况下继续发送到服务器。有什么建议我可以使用吗?比如后台工作人员之类的?我试过按键,但效果不太好。我会尝试任何建议,谢谢。
第一个代码是我的服务器代码在控制台应用程序和第二个代码是我的客户端代码在windows窗体应用程序。
namespace TcpIpNewServer
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(">> Server started...");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(">> Accepted connection from client...");
while ((true))
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
if (bytesFrom[0].ToString() != "0") //listen from client
{
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$^$~~)(")); //hardcode
Console.WriteLine("<< Client : " + dataFromClient);
}
//var cki = Console.ReadKey(true);
//if (cki.KeyChar == 't')
//{
string serverResponse = Console.ReadLine();
if (serverResponse != null) //write to client
{
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
//}
}
}
}
}
客户机代码public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Msg("Client started...");
try
{
clientSocket.Connect("127.0.0.1", 8888);
NetworkStream serverStream = clientSocket.GetStream();
label1.Text = "Client Socket Program - Server connected...";
}
catch (Exception ex)
{
label1.Text = "Client Socket Program - Server connection failed... Please try again...Make sure server is on...";
}
}
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
private void button1_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
if (textBox1.Text != "" && textBox1.Text != null) //write to the server
{
//string trimDataText = Regex.Replace(textBox1.Text, @"s", "");
string cloneTextbox = textBox1.Text + "$^$~~)(";
Msg("Me: " + textBox1.Text);
textBox1.Text = "";
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(cloneTextbox);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
byte[] inStream = new byte[10025]; //read from the server
//if (inStream[0].ToString() != "0")
//{
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
Msg2("Server: " + returndata);
//}
}
private void Msg(string mesg)
{
richTextBox1.Text = richTextBox1.Text + Environment.NewLine + ">> " + mesg;
}
private void Msg2(string mesg)
{
richTextBox1.Text = richTextBox1.Text + Environment.NewLine + "<< " + mesg;
}
你需要切换到异步读/写。NetworkStream.BeginRead()