我是C#的新手,我开发了一个Socket程序。
Listen(backlog)
但是在服务器响应客户端之后,服务器已关闭,不会随时收听。在调用using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PC_Client
{
public partial class Form1 : Form
{
private static Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Form1()
{
InitializeComponent();
Console.ReadLine();
}
private void SendLoop()
{
string req = txtRequest.Text;
byte[] buffer = Encoding.ASCII.GetBytes(req);
clientSocket.Send(buffer);
byte[] receiveBuf = new byte[1024];
int rec = clientSocket.Receive(receiveBuf);
byte[] data = new byte[rec];
Array.Copy(receiveBuf, data, rec);
Console.WriteLine("Received: " + Encoding.ASCII.GetString(data));
}
private void LoopConnect()
{
int attempts = 0;
while(!clientSocket.Connected)
{
try
{
attempts++;
clientSocket.Connect(IPAddress.Loopback, 100);
}
catch (SocketException)
{
Console.WriteLine("Connection attempts: " + attempts.ToString());
}
}
//Console.Clear();
Console.WriteLine("Connected");
}
private void button1_Click(object sender, EventArgs e)
{
SendLoop();
}
}
}
以维护服务器很长时间后,我该如何重置服务器?
这是我在ClientSide中的代码:
- get players tile location.
- get each tile in that stack ( aka, get a reference to every tile in that cell across each layer.
- check for visibility exceptions on each of those tiles. Store exceptions as properties defined in Tiled. ( will cover properties shortly )
- handle accordingly, most likely by raising or lowering the players render layer for that frame.
答案 0 :(得分:0)
我不确定C#的细节,但一般来说,你想把你的接受调用包装成这样的循环:
while(true) {
clientSocket = serverSocket.accept();
respond to socket in background thread
}
这样,您的主线程将始终能够侦听套接字(因为它包含在while循环中,并继续接受新连接),同时在处理客户端请求时也不会被阻塞(因为客户端套接字被处理)在后台线程中)