我在控制台中有一个简单的聊天客户端。这是代码
服务器用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace chat_server
{
class Program
{
static TcpListener server = new TcpListener(IPAddress.Any, 9999);
static void input(object obs)
{
StreamWriter writer = obs as StreamWriter;
string op = "nothing";
while (!op.Equals("exit"))
{
Console.ResetColor();
Console.WriteLine("This is the " + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Enter your text(type exit to quit)");
op = Console.ReadLine();
writer.WriteLine(op);
writer.Flush();
}
}
static void output(Object obs)
{
StreamReader reader = obs as StreamReader;
Console.ForegroundColor = ConsoleColor.Green;
while (true)
{
Console.WriteLine(reader.ReadLine());
}
}
static void monitor()
{
while (true)
{
TcpClient cls = server.AcceptTcpClient();
Thread th = new Thread(new ParameterizedThreadStart(mul_stream));
th.Start(cls);
}
}
static void mul_stream(Object ob)
{
TcpClient client = ob as TcpClient;
Stream streams = client.GetStream();
StreamReader reads = new StreamReader(streams);
StreamWriter writs = new StreamWriter(streams);
new Thread(new ParameterizedThreadStart(output)).Start(reads);
input(writs);
}
static void Main(string[] args)
{
server.Start();
monitor();
server.Stop();
Console.ReadKey();
}
}
}
这是客户端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace chat_client
{
class Program
{
static StreamReader reader;
static StreamWriter writer;
static Thread input_thread;
static void input()
{
string op = "nothing";
while (!op.Equals("exit"))
{
Console.ResetColor();
Console.WriteLine("Enter your text(type exit to quit)");
op = Console.ReadLine();
writer.WriteLine(op);
writer.Flush();
}
}
static void output()
{
Console.ForegroundColor = ConsoleColor.Blue;
while (true)
{
Console.WriteLine(reader.ReadLine());
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter the ip address");
string ip = Console.ReadLine();
TcpClient client = new TcpClient(ip,9999);
NetworkStream stream = client.GetStream();
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
input_thread = new Thread(input);
input_thread.Start();
/*
writer.Write("Hello world");
writer.Flush();
Console.WriteLine("Message Sent");*/
output();
client.Close();
Console.ReadKey();
}
}
}
现在的问题是我在将此代码转换为 GUI 时遇到了一些问题。例如,服务器中通过特定流向客户端传递消息的输入功能应该在某种程度上等同于 GUI 中的 SEND 按钮。
然而,每个线程都会创建自己的流,我认为在不同的线程上创建单独的事件处理程序不是一个好主意。
简而言之,我需要一些关于从哪里开始这个项目的建议。
谢谢你。