我在c#中創建了一個服務器客戶端應用程序。我設法從客戶端發送消息到服務器並閱讀它們,但我不知道如何從服務器發回消息到客戶端。從服務器發送消息到客戶端c#
namespace TCPSockets {
public partial class Form1 : Form {
TcpClient client = null;
TcpListener listener = null;
IPAddress ip = null;
int port = 1337;
Thread thClient = null;
Thread thListener = null;
NetworkStream dataStream = null;
public Form1() {
InitializeComponent();
txt_ip.Text = "127.0.0.1";
txt_port.Text = "1234";
}
private void ListenForConnections() {
listener = new TcpListener(ip, port);
listener.Start();
while (true) {
try {
client = listener.AcceptTcpClient();
dataStream = client.GetStream();
byte[] message = new byte[1024];
dataStream.Read(message, 0, message.Length);
dataStream.Close();
string strMessage = Encoding.UTF8.GetString(message);
MessageBox.Show("Server: I got message: " + strMessage);
}
catch (Exception ex) {
thListener.Join();
}
}
}
private void start_server_Click(object sender, EventArgs e)
{
ip = IPAddress.Parse(txt_ip.Text);
port = Convert.ToInt32(txt_port.Text);
// nit => sicer vmesnik blokira, ko kličemo AcceptTcpClient()
thListener = new Thread(new ThreadStart(ListenForConnections));
thListener.IsBackground = true;
thListener.Start();
}
}
}
namespace TCPSockets {
public partial class Form1 : Form {
TcpClient client = null;
TcpListener listener = null;
IPAddress ip = null;
int port = 1337;
Thread thClient = null;
Thread thListener = null;
NetworkStream dataStream = null;
public Form1() {
InitializeComponent();
txt_ip.Text = "127.0.0.1";
txt_port.Text = "1234";
}
private void SendPacket(object pClient) {
string message = txt_message.Text;
try {
client = (TcpClient)pClient;
client.Connect(ip, port);
dataStream = client.GetStream();
byte[] strMessage = Encoding.UTF8.GetBytes(message);
dataStream.Write(strMessage, 0, strMessage.Length);
dataStream.Close();
client.Close();
}
catch (Exception ex) {
MessageBox.Show("Odjemalec: Pošiljanje ni bilo uspešno!");
}
}
private void send_to_server_Click(object sender, EventArgs e)
{
ip = IPAddress.Parse(txt_ip.Text);
port = Convert.ToInt32(txt_port.Text);
client = new TcpClient();
thClient = new Thread(new ParameterizedThreadStart(SendPacket));
thClient.IsBackground = true;
thClient.Start(client);
}
}
}
沒有人知道如何正確地從服務器發送消息給客戶端和客戶端閱讀?
首先客戶端必須連接到服務器。然後讓服務器寫入流,並從流中讀取客戶端。這與你已有的東西沒有多大區別。 – AlexDev
請嘗試以下方法:listener.Server。發送 – jdweng
您可以使用與從客戶端發送到服務器的方式完全相同的方式將消息從服務器發送到客戶端。只是不要關閉插座。確保你閱讀了可用的參考資料,包括MSDN示例和非常有用的[Winsock程序員常見問題](http://tangentsoft.net/wskfaq/)。它是Winsock程序員在.NET中編寫的,但.NET API只是Winsock上的一個薄層,並且其中的大多數建議仍然適用。 –