我创建了TCP服务器。它从客户端获取消息,我想发送回响应:"test meesage"
。我想这次我必须使用TCPClient
课,但我不确定,我不知道为什么。我已经有他们之间的联系,也许我可以重用它?我在代码中标记为注释位置,我想将消息发回。
如何将邮件发送回客户端?(在代码底部标记为注释)
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace HomeSecurity {
class TCPEventServer {
private TcpListener tcpListener;
private Thread listenThread;
public static readonly string SWITCH = "SWITCH";
public TCPEventServer() {
this.tcpListener = new TcpListener(IPAddress.Any, 13000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients() {
this.tcpListener.Start();
while (true) {
TcpClient client = this.tcpListener.AcceptTcpClient();
System.Media.SoundPlayer notificationPlayer = new System.Media.SoundPlayer("beep.wav");
notificationPlayer.Play();
System.Diagnostics.Debug.WriteLine("przyszlo cos");
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client) {
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
System.Diagnostics.Debug.WriteLine("przyszlo cos");
while (true) {
bytesRead = 0;
try {
bytesRead = clientStream.Read(message, 0, 4096);
System.Diagnostics.Debug.WriteLine("przyszlo cos");
} catch {
break;
}
if (bytesRead == 0) {
break;
}
//wiadomość została pomyślnie odczytana
ASCIIEncoding encoder = new ASCIIEncoding();
string messageDecoded = encoder.GetString(message, 0, bytesRead);
messageDecoded = messageDecoded.Replace("\r", string.Empty).Replace("\n", string.Empty);
string ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address + "";
Console.WriteLine("message: " + messageDecoded + " ip: " + ip);
if (messageDecoded.Split(' ')[0].Equals(SWITCH)) {
//przeprowadzenie autoryzacji
string login = messageDecoded.Split(' ')[1];
string password = messageDecoded.Split(' ')[2];
if (authorized(login, password)) {
VideoStream.SECURED = !VideoStream.SECURED;
System.Diagnostics.Debug.WriteLine("System secured: " + VideoStream.SECURED);
sendResponse();
//I WOULD LIKE TO SEND MESSAGE BACK TO THE CLIENT HERE
}
} else {
VideoStream.PassMessage(messageDecoded, ip);
}
}
tcpClient.Close();
}
private void sendResponse() {
}
private bool authorized(string login, string password) {
return true;
}
}
}
答案 0 :(得分:1)
您需要将clientStream更改为成员变量:
private NetworkStream _clientStream ;
private void HandleClientComm(object client) {
TcpClient tcpClient = (TcpClient)client;
_clientStream = tcpClient.GetStream();
...
}
然后,使用流来编写数据:
private void sendResponse()
{
var buffer = Encoding.ASCII.GetBytes("Hello!");
_clientStream.Write(buffer, 0, buffer.Length);
}