C#怎么写出开服器中的控制台
控制台就类似这样可以显示信息的控制台
不用很复杂,实现功能就可以了
private TcpClient client = null;
private TcpListener server = null;
private bool stopped = false;
private void button1_Click(object sender, EventArgs e)
{
//IPAddress localIp = Dns.GetHostAddresses("localhost")[0];
server = new TcpListener(12345);
server.Start();
showInfo("服务端启动 ..");
Thread thServer = new Thread(serverHandler) { IsBackground = true};
thServer.Start(server);
client = new TcpClient();
client.Connect("127.0.0.1", 12345);
if (client.Connected)
showInfo("客户端已经连接: " + client.Client.RemoteEndPoint.ToString());
else
showInfo("未连接上服务端.");
if (client.Connected)
{
Thread th = new Thread(clientHandler) { IsBackground = true };
th.Start(client);
}
}
private void serverHandler(object obj)
{
TcpListener svr = (TcpListener)obj;
while (!stopped)
{
try
{
TcpClient tcpClient=null;
if (svr.Pending())
{
tcpClient = svr.AcceptTcpClient();
Thread th = new Thread(serverClientHandler) { IsBackground = true };
th.Start(tcpClient);
showInfo("服务端接收连接, 并开始通讯: " + tcpClient.Client.RemoteEndPoint.ToString());
}
else
{
showInfo("暂时无连接请求:");
Thread.Sleep(60000);
}
}
catch(Exception ex)
{
showInfo("服务端监听连接异常: " + ex.Message);
Thread.Sleep(1000);
}
}
}
// 服务端处理连接
private void serverClientHandler(object obj)
{
byte[] buf = new byte[1024];
TcpClient client = (TcpClient)obj;
while (!stopped && client.Connected)
{
try
{
showInfo("等待客户端指令 ..");
int count = client.Client.Receive(buf);
if (count > 0)
{
//parse
string cmd = Encoding.Default.GetString(buf, 0, count);
showInfo("收到客户端指令: " +cmd);
switch (cmd)
{
case "OK":
client.Client.Send(Encoding.Default.GetBytes(cmd));
break;
default:
break;
}
}
}
catch (Exception ex)
{
showInfo("接收客户端指令超时: " + ex.Message);
}
}
}
// 客户端处理连接
private void clientHandler(object obj)
{
byte[] buf = new byte[1024];
TcpClient client = (TcpClient)obj;
client.Client.Send(Encoding.Default.GetBytes("OK"));
while (!stopped && client.Connected)
{
try
{
int count = client.Client.Receive(buf);
if (count > 0)
{
//parse
}
}
catch (Exception ex)
{
showInfo("接收服务端数据超时: " + ex.Message);
}
}
}