用C#编写一简单聊天程序
发布网友
发布时间:2022-04-25 20:18
我来回答
共2个回答
热心网友
时间:2022-06-17 02:43
客户端:namespace chatClient
{
public partial class Client : Form
{
delegate void SetTextCallback(string text);
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.TextBox displayTextBox;
private NetworkStream output;
private BinaryWriter writer;
private BinaryReader reader; private string message = "";
private Thread readThread;
private System.ComponentModel.Container components = null; public Client()
{
InitializeComponent(); readThread = new Thread(new ThreadStart(RunClient));
readThread.Start();
} //[STAThread] //static void Main()
//{ Application.Run(new Client()); } protected void Client_Closing(object sender, CancelEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
} private void inputTextBox_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter)
{
writer.Write("客户:" + inputTextBox.Text);
this.displayTextBox.Text += "\r\n客户:" + this.inputTextBox.Text; this.inputTextBox.Text = ""; }//end if }//end try
catch (SocketException ioe)
{
displayTextBox.Text += "\n写入文件错误。";
}
}//end inputTextBox_KeyDown public void RunClient()
{
TcpClient client; try
{
this.SetText("正在连接\r\n");
client = new TcpClient();
client.Connect("localhost", 5000); output = client.GetStream(); writer = new BinaryWriter(output);
reader = new BinaryReader(output); //displayTextBox.Text += ;
this.SetText("\r\n 获取输入、输出流\r\n");
inputTextBox.ReadOnly = false; do
{
try
{
message = reader.ReadString();
this.SetText("\r\n" + message);
}
catch (Exception)
{ System.Environment.Exit(System.Environment.ExitCode); } } while (message != "服务器>>>terminate"); this.SetText("\r\n关闭连接。\r\n");
writer.Close();
reader.Close();
output.Close();
client.Close();
Application.Exit(); }//end try
catch (Exception err)
{ MessageBox.Show(err.ToString()); } }//end method private void SetText(string text)
{
// InvokeRequired需要比较调用线程ID和创建线程ID
// 如果它们不相同则返回true
if (this.displayTextBox.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.displayTextBox.Text += text;
}
}
}//end class
}
热心网友
时间:2022-06-17 02:44
五分一个全套的程序,c#什么时候这么不值钱了