gpt4 book ai didi

c# - 我如何在同一端口上同时使用套接字发送和接收

转载 作者:可可西里 更新时间:2023-11-01 02:43:44 26 4
gpt4 key购买 nike

我正在尝试做聊天应用程序,我正在使用 tcp 套接字和线程问题是我如何在同一个套接字上同时等待命令和发送命令

public void GetTextFather()
{
string Command = "";
string text = "";
while (Command == "")
Command = Functions.serverrecievetext(ip, port);

if (Command == "Text")
{
while (text == "")
text = Functions.serverrecievetext(ip, port);
if (text != "")
{

listBox1.Invoke((MethodInvoker)delegate { this.listBox1.Items.Add(name + ":" + text); });
Thread t = new Thread(GetTextFather);
t.Start();
}

}
if (Command == "Typing")
{
label1.Invoke((MethodInvoker)delegate { label1.Visible = true; });
Thread t = new Thread(GetTextFather);
t.Start();
}
if (Command == "NotTyping")
{
label1.Invoke((MethodInvoker)delegate { label1.Visible = false; });
Thread t = new Thread(GetTextFather);
t.Start();
}

}

点击发送按钮

 private void button1_Click(object sender, EventArgs e)
{string text=textBox1.Text;
listBox1.Items.Add("You:" + text);
if (text.Length != 0)
{
if (!flag)
{Functions.ClientSendTextPortsixty("Text", port);
Functions.ClientSendTextPortsixty(text, port);

}
else
{Functions.ServerSendbyip("Text", ip, port);
Functions.ServerSendbyip(text, ip, port);

}
}
textBox1.Text = "";
}

函数send 很简单,通过socket 发送一个文本,receive 得到一个文本。我有 GetTextSon() 和 GetTextFather 一样如果您需要更多信息,请在下方评论

最佳答案

也许我没有正确理解问题,但这段代码在过去对我有用。我将忽略 UI 部分,只编写套接字代码(这是来自内存,但应该非常接近):

public class ChatClient
{
public event Action<String> MessageRecieved;

private TcpClient socket;
public ChatClient(String host, int port)
{
socket = new TcpClient(host, port);
Thread listenThread = new Thread(ReadThread);
listenThread.Start();
}

private void ReadThread()
{
NetworkStream netStream = socket.GetStream ();
while (socket.Connected)
{
//Read however you want, something like:
// Reads NetworkStream into a byte buffer.
byte[] bytes = new byte[socket.ReceiveBufferSize];

// Read can return anything from 0 to numBytesToRead.
// This method blocks until at least one byte is read.
netStream.Read (bytes, 0, (int)socket.ReceiveBufferSize);

// Returns the data received from the host to the console.
MessageRecieved(Encoding.UTF8.GetString (bytes));
}
}

public void SendMessage(string msg)
{
NetworkStream netStream = socket.GetStream ();
Byte[] sendBytes = Encoding.UTF8.GetBytes (msg);
netStream.Write (sendBytes, 0, sendBytes.Length);
}
}

现在,为了解决差异化问题,我将所有消息分成两部分,“命令”和“数据”。例如,如果您想发送“踢出用户”命令:

Send: "KickUser:bob"
Recieve: "UserKicked:bob"

来自其他用户的聊天消息类似于:

Recieve: "ChatMessage:Hi"

使用客户端的人只需监听 MessageRecieved 事件并适本地解析消息,引发 UI 更新所需的任何事件。

让我知道你的想法!

关于c# - 我如何在同一端口上同时使用套接字发送和接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22386649/

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