我一直在观看以下关于如何创建TCP / IP连接的视频:Server 和Client 我需要做的是创建一个游戏(翻转卡),其中我只发送一个矩阵的2个坐标。而已。或者更少。
(代码将遵循)
从我观察到的情况来看,每次发送消息时,他都会关闭并重新打开连接。它正在发挥作用。但是,我在代码中进行修改以保持连接打开,检测邮件何时到达?
我所有的谷歌搜索都让我看到了这两种方法:
点击启动服务器
private void bStartServer_Click(object sender, EventArgs e)
{
Thread tcpServerRunThread = new Thread(new ThreadStart(TCPServerRun));
tcpServerRunThread.Start();
}
服务器运行并等待连接
private void TCPServerRun()
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 2016);
tcpListener.Start();
updateUI("Listening");
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
updateUI("Connected");
Thread tcpHandlerThread = new Thread(new ParameterizedThreadStart(tcpHandler));
tcpHandlerThread.Start(client);
}
}
我处理了我的消息
private void tcpHandler(object client)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 5004);
TcpClient mClient = (TcpClient)client;
NetworkStream stream = mClient.GetStream();
byte[] message = new byte[1024];
stream.Read(message,0, message.Length);
updateUI("New message = " + Encoding.ASCII.GetString(message));
stream.Close();
mClient.Close();
}
注意:updateUI
是他为更新列表框项而制作的功能
客户端 - 几乎与服务器端一样 `private void button1_Click(object sender,EventArgs e) { 线程mThread =新线程(新的ThreadStart(ConnectAsClient)); mThread.Start(); }
private void ConnectAsClient()
{
// aici putem inlocui cu adresa de IP dorita
//client.Connect(IPAddress.Parse(textBox.Text), 5004);
client = new TcpClient();
//client.Connect(IPAddress.Parse("127.0.0.1"), 2016); // for when I'm not connected to network
client.Connect(IPAddress.Parse("my_ip_here"), 2016); // for when I am connected to the network
updateUI("connected");
NetworkStream stream = client.GetStream();
string s = "Hello world!";
byte[] message = Encoding.ASCII.GetBytes(s);
stream.Write(message, 0, message.Length);
this.updateUI("Message sent!");
stream.Close();
// client.Close();
}`
如果我没错,每次他再次连接时,他都会创建一个新连接,而不是打开旧连接,对吧? (这是我第一次使用TCP / IP,自己学习,所以如果可能的话我宁愿不使用套接字)
-------------------------------------------- ---------------------------
我的代码的完整链接(从开头提供的视频略微修改):
答案 0 :(得分:0)
每次发送邮件时都会重新连接。为此使用两种不同的方法;一个用于连接到服务器,另一个用于实际发送消息。像这样:
TcpClient client;
private void ConnectAsClient()
{
//client.Connect(IPAddress.Parse(textBox.Text), 5004);
client = new TcpClient();
//client.Connect(IPAddress.Parse("127.0.0.1"), 2016);
client.Connect(IPAddress.Parse("my_ip_here"), 2016);
updateUI("connected");
}
void SendMessage()
{
NetworkStream stream = client.GetStream();
string s = "Hello world!";
byte[] message = Encoding.ASCII.GetBytes(s);
stream.Write(message, 0, message.Length);
this.updateUI("Message sent!");
}