简单Socket示例

 

Server UI
namespace SocketTest
{
    
partial class Server
    {
        
/// <summary>
        
/// 必需的设计器变量。
        
/// </summary>
        private System.ComponentModel.IContainer components = null;

        
/// <summary>
        
/// 清理所有正在使用的资源。
        
/// </summary>
        
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            
if (disposing && (components != null))
            {
                components.Dispose();
            }
            
base.Dispose(disposing);
        }

        
#region Windows 窗体设计器生成的代码

        
/// <summary>
        
/// 设计器支持所需的方法 - 不要
        
/// 使用代码编辑器修改此方法的内容。
        
/// </summary>
        private void InitializeComponent()
        {
            
this.btnOpen = new System.Windows.Forms.Button();
            
this.textBox_port = new System.Windows.Forms.TextBox();
            
this.label1 = new System.Windows.Forms.Label();
            
this.textBox_send = new System.Windows.Forms.TextBox();
            
this.button_Send = new System.Windows.Forms.Button();
            
this.label2 = new System.Windows.Forms.Label();
            
this.label3 = new System.Windows.Forms.Label();
            
this.listView_userlist = new System.Windows.Forms.ListView();
            
this.richTextBox_record = new System.Windows.Forms.RichTextBox();
            
this.SuspendLayout();
            
// 
            
// btnOpen
            
// 
            this.btnOpen.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            
this.btnOpen.Location = new System.Drawing.Point(171285);
            
this.btnOpen.Name = "btnOpen";
            
this.btnOpen.Size = new System.Drawing.Size(7520);
            
this.btnOpen.TabIndex = 1;
            
this.btnOpen.Text = "启动服务";
            
this.btnOpen.UseVisualStyleBackColor = true;
            
this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click);
            
// 
            
// textBox_port
            
// 
            this.textBox_port.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            
this.textBox_port.Location = new System.Drawing.Point(85285);
            
this.textBox_port.Name = "textBox_port";
            
this.textBox_port.Size = new System.Drawing.Size(6020);
            
this.textBox_port.TabIndex = 2;
            
this.textBox_port.Text = "2001";
            
// 
            
// label1
            
// 
            this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            
this.label1.AutoSize = true;
            
this.label1.Location = new System.Drawing.Point(12288);
            
this.label1.Name = "label1";
            
this.label1.Size = new System.Drawing.Size(6713);
            
this.label1.TabIndex = 3;
            
this.label1.Text = "监听端口:";
            
// 
            
// textBox_send
            
// 
            this.textBox_send.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        
| System.Windows.Forms.AnchorStyles.Right)));
            
this.textBox_send.Location = new System.Drawing.Point(128218);
            
this.textBox_send.Multiline = true;
            
this.textBox_send.Name = "textBox_send";
            
this.textBox_send.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            
this.textBox_send.Size = new System.Drawing.Size(35845);
            
this.textBox_send.TabIndex = 4;
            
this.textBox_send.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox2_KeyPress);
            
// 
            
// button_Send
            
// 
            this.button_Send.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            
this.button_Send.Enabled = false;
            
this.button_Send.Location = new System.Drawing.Point(492217);
            
this.button_Send.Name = "button_Send";
            
this.button_Send.Size = new System.Drawing.Size(4546);
            
this.button_Send.TabIndex = 5;
            
this.button_Send.Text = "发送信息";
            
this.button_Send.UseVisualStyleBackColor = true;
            
this.button_Send.Click += new System.EventHandler(this.button_Send_Click);
            
// 
            
// label2
            
// 
            this.label2.AutoSize = true;
            
this.label2.Location = new System.Drawing.Point(129);
            
this.label2.Name = "label2";
            
this.label2.Size = new System.Drawing.Size(5513);
            
this.label2.TabIndex = 7;
            
this.label2.Text = "用户列表";
            
// 
            
// label3
            
// 
            this.label3.AutoSize = true;
            
this.label3.Location = new System.Drawing.Point(1259);
            
this.label3.Name = "label3";
            
this.label3.Size = new System.Drawing.Size(3113);
            
this.label3.TabIndex = 8;
            
this.label3.Text = "消息";
            
// 
            
// listView_userlist
            
// 
            this.listView_userlist.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        
| System.Windows.Forms.AnchorStyles.Left)));
            
this.listView_userlist.Location = new System.Drawing.Point(1525);
            
this.listView_userlist.Name = "listView_userlist";
            
this.listView_userlist.Size = new System.Drawing.Size(107238);
            
this.listView_userlist.TabIndex = 9;
            
this.listView_userlist.UseCompatibleStateImageBehavior = false;
            
this.listView_userlist.View = System.Windows.Forms.View.List;
            
this.listView_userlist.SelectedIndexChanged += new System.EventHandler(this.listView_userlist_SelectedIndexChanged);
            
// 
            
// richTextBox_record
            
// 
            this.richTextBox_record.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        
| System.Windows.Forms.AnchorStyles.Left)
                        
| System.Windows.Forms.AnchorStyles.Right)));
            
this.richTextBox_record.BackColor = System.Drawing.SystemColors.Window;
            
this.richTextBox_record.HideSelection = false;
            
this.richTextBox_record.Location = new System.Drawing.Point(12826);
            
this.richTextBox_record.Name = "richTextBox_record";
            
this.richTextBox_record.ReadOnly = true;
            
this.richTextBox_record.Size = new System.Drawing.Size(409186);
            
this.richTextBox_record.TabIndex = 10;
            
this.richTextBox_record.Text = "";
            
// 
            
// Server
            
// 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            
this.ClientSize = new System.Drawing.Size(549310);
            
this.Controls.Add(this.richTextBox_record);
            
this.Controls.Add(this.listView_userlist);
            
this.Controls.Add(this.label3);
            
this.Controls.Add(this.label2);
            
this.Controls.Add(this.button_Send);
            
this.Controls.Add(this.textBox_send);
            
this.Controls.Add(this.label1);
            
this.Controls.Add(this.textBox_port);
            
this.Controls.Add(this.btnOpen);
            
this.Name = "Server";
            
this.Text = "服务器(TcpListener)";
            
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Server_FormClosing);
            
this.ResumeLayout(false);
            
this.PerformLayout();

        }

        
#endregion

        
private System.Windows.Forms.Button btnOpen;
        
private System.Windows.Forms.TextBox textBox_port;
        
private System.Windows.Forms.Label label1;
        
private System.Windows.Forms.TextBox textBox_send;
        
private System.Windows.Forms.Button button_Send;
        
private System.Windows.Forms.Label label2;
        
private System.Windows.Forms.Label label3;
        
private System.Windows.Forms.ListView listView_userlist;
        
private System.Windows.Forms.RichTextBox richTextBox_record;
    }
}

 

 

Server
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace SocketTest
{
    
public partial class Server : Form
    {
        
int selectIndex = 0;
        Thread serverThread;
        Thread clientThread;
        TcpListener listener;
        TcpClient clientTcp;
        Dictionary
<IPHostEntry, TcpClient> userList = new Dictionary<IPHostEntry, TcpClient>();
        Encoding encoding 
= Encoding.UTF8;
        
string record = "";
        
string welcome = "Welcome to Sever ";
        
bool isRun = true;
        
public Server()
        {
            InitializeComponent();
        }

        
private void ServerStart()
        {
            
try
            {
                
//创建IPEndPoint实例
                IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse(textBox_port.Text));

                listener 
= new TcpListener(ipep);
                listener.Start(
100);

                
while (isRun)
                {
                    
//在套接字上接收接入的连接
                    clientTcp = listener.AcceptTcpClient();
                    IPEndPoint temp 
= (IPEndPoint)clientTcp.Client.RemoteEndPoint;
                    IPHostEntry userpc 
= Dns.GetHostEntry(temp.Address);
                    AddUser(userpc, clientTcp);
                    clientThread 
= new Thread(new ThreadStart(ReceiveData));
                    clientThread.Start();
                }
                listener.Stop();
            }
            
catch (Exception ex)
            {
                MessageBox.Show(
"listening Error: " + ex.Message);
            }
            
finally
            {
                listener.Stop();
            }
        }

        
private void ReceiveData()
        {
            TcpClient client 
= clientTcp;
            NetworkStream ns 
= client.GetStream();
            Byte[] buffer 
= new Byte[1024];

            
//根据收听到的客户端套接字向客户端发送信息
            IPEndPoint ip = (IPEndPoint)client.Client.RemoteEndPoint;
            IPHostEntry userpc 
= Dns.GetHostEntry(ip.Address);

            record 
= Environment.NewLine + ip.Address + "(" + ip.Port + ") Connected!";
            ReshUI();
            
byte[] data = new byte[1024];
            data 
= encoding.GetBytes(welcome);
            ns.Write(data, 
0, data.Length);

            
while (isRun)
            {
                
//在套接字上接收客户端发送的信息
                int bufLen = 0;
                
try
                {
                    bufLen 
= client.Available;
                    
if (bufLen > 0)
                    {
                        ns.Read(buffer, 
0, bufLen);
                        record 
= encoding.GetString(buffer).Substring(0, bufLen);
                        
//保存接受消息
                        string message = string.Format("{0}{1}({2}):{3}    {4}", Environment.NewLine, Environment.UserName, DateTime.Now.ToString("HH:mm:ss"), Environment.NewLine, "Received");
                        ReshUI();
                        
//反馈接受
                        WriteReceiveMessage(client, message);
                    }
                    
if (bufLen == 0)
                        
continue;
                }
                
catch (Exception ex)
                {
                    MessageBox.Show(
"Receive Error:" + ex.Message);
                    
return;
                }
            }
            client.Close();
        }

        
void WriteReceiveMessage(TcpClient client, string message)
        {
            
try
            {
                
byte[] buffer = encoding.GetBytes(message);
                client.GetStream().Write(buffer, 
0, buffer.Length);
            }
            
catch (Exception ex)
            {
                MessageBox.Show(ex.Message 
+ "--" + ex.StackTrace);
            }
        }

        
void AddUser(IPHostEntry userEntry, TcpClient tcpClient)
        {
            
foreach (KeyValuePair<IPHostEntry, TcpClient> user in userList)
            {
                
if (user.Value.Client.RemoteEndPoint.Equals(tcpClient.Client.RemoteEndPoint))
                    
return;
            }
            userList.Add(userEntry, tcpClient);
            
//listView1.Items.Add(ip);
        }

        
string GetLocalIP()
        {
            
string strHostIP = "";
            IPHostEntry oIPHost 
= Dns.GetHostEntry(Environment.MachineName);
            
if (oIPHost.AddressList.Length > 0)
                strHostIP 
= oIPHost.AddressList[0].ToString();
            
return strHostIP;
        }

        
void ReshUI()
        {

            
//while (true)
            
//{
            MethodInvoker mi = new MethodInvoker(ShowUIData);
            
this.Invoke(mi);
            Thread.Sleep(
500);
            
//}
        }

        
void ShowUIData()
        {
            richTextBox_record.Text 
+= record;
            listView_userlist.Items.Clear();
            
foreach (KeyValuePair<IPHostEntry, TcpClient> kp in userList)
            {
                
if (!kp.Value.Client.Connected)
                {
                    userList.Remove(kp.Key);
                    
continue;
                }
                IPEndPoint temp 
= (IPEndPoint)kp.Value.Client.RemoteEndPoint;
                ListViewItem lvi 
= new ListViewItem(kp.Key.HostName + "(" + temp.Port + ")");
                lvi.Tag 
= temp;
                listView_userlist.Items.Add(lvi);

            }
            
if (listView_userlist.Items.Count > 0)
            {
                listView_userlist.Items[selectIndex].Checked 
= true;
                listView_userlist.Items[selectIndex].Selected 
= true;
                listView_userlist.EnsureVisible(selectIndex);
                listView_userlist.HideSelection 
= false;
            }
            record 
= "";

            richTextBox_record.SelectionStart 
= richTextBox_record.TextLength > 0 ? richTextBox_record.TextLength - 1 : 0;
            richTextBox_record.SelectionLength 
= 0;
        }

        
private void listView_userlist_SelectedIndexChanged(object sender, EventArgs e)
        {
            
if (listView_userlist.Items.Count > 0 && listView_userlist.SelectedItems.Count > 0)
                selectIndex 
= listView_userlist.SelectedItems[0].Index;
        }

        
private void btnOpen_Click(object sender, EventArgs e)
        {
            
try
            {
                
//if (listener != null)
                
//{
                
//    try
                
//    {
                
//        isRun = false;
                
//        if (clientTcp != null)
                
//        {
                
//            clientTcp.Close();
                
//            clientTcp.Client.Shutdown(SocketShutdown.Both);
                
//            clientTcp.Client.Close();
                
//        }
                
//        listener.Server.Close();
                
//        listener.Server.Shutdown(SocketShutdown.Both);
                
//        listener.Server.Close();
                
//        listener.Stop();
                
//    }
                
//    finally
                
//    {
                
//        clientTcp.Close();
                
//        listener.Stop();
                
//    }
                
//}
                
//else
                
//{
                serverThread = new Thread(new ThreadStart(ServerStart));
                serverThread.Start();
                richTextBox_record.Text 
+= Environment.NewLine + "----Server Start ...----";
                Thread ui 
= new Thread(new ThreadStart(ReshUI));
                ui.Start();
                button_Send.Enabled 
= true;
                
//btnOpen.Enabled = false;
                
//}
            }
            
catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        
void ToLastPosition()
        {

        }

        
private void Server_FormClosing(object sender, FormClosingEventArgs e)
        {
            Environment.Exit(
0);
        }

        
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            
if (e.KeyChar == (char)Keys.Enter)
            {
                button_Send_Click(
nullnull);
                e.Handled 
= true;

            }
        }

        
private void button_Send_Click(object sender, EventArgs e)
        {
            
if (textBox_send.Text.Length > 0)
            {
                
if (listView_userlist.SelectedItems.Count < 1)
                {
                    MessageBox.Show(
"请选择要通信的IP");
                    
return;
                }
                
string message = Environment.NewLine + string.Format("{0}({1}):{2}    {3}", Environment.UserName, DateTime.Now.ToString("HH:mm:ss"), Environment.NewLine, textBox_send.Text);
                richTextBox_record.Text 
+= message;
                richTextBox_record.SelectionStart 
= richTextBox_record.TextLength > 0 ? richTextBox_record.TextLength - 1 : 0;
                richTextBox_record.SelectionLength 
= 0;
                textBox_send.Clear();
                textBox_send.Focus();
                
foreach (ListViewItem li in listView_userlist.SelectedItems)
                {
                    
foreach (KeyValuePair<IPHostEntry, TcpClient> kp in userList)
                    {
                        
//(EndPoint)li.Tag;
                        if (li.Tag.Equals(kp.Value.Client.RemoteEndPoint))
                        {
                            WriteReceiveMessage(kp.Value, message);
                        }
                    }
                }

            }
        }
    }
}

 

 

Client UI 
namespace Client
{
    
partial class Client
    {
        
/// <summary>
        
/// 必需的设计器变量。
        
/// </summary>
        private System.ComponentModel.IContainer components = null;

        
/// <summary>
        
/// 清理所有正在使用的资源。
        
/// </summary>
        
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            
if (disposing && (components != null))
            {
                components.Dispose();
            }
            
base.Dispose(disposing);
        }

        
#region Windows 窗体设计器生成的代码

        
/// <summary>
        
/// 设计器支持所需的方法 - 不要
        
/// 使用代码编辑器修改此方法的内容。
        
/// </summary>
        private void InitializeComponent()
        {
            
this.textBox_send = new System.Windows.Forms.TextBox();
            
this.btnSend = new System.Windows.Forms.Button();
            
this.linkLabel_connect = new System.Windows.Forms.LinkLabel();
            
this.label1 = new System.Windows.Forms.Label();
            
this.label2 = new System.Windows.Forms.Label();
            
this.textBox2 = new System.Windows.Forms.TextBox();
            
this.textBox1 = new System.Windows.Forms.TextBox();
            
this.richTextBox_record = new System.Windows.Forms.RichTextBox();
            
this.SuspendLayout();
            
// 
            
// textBox_send
            
// 
            this.textBox_send.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        
| System.Windows.Forms.AnchorStyles.Right)));
            
this.textBox_send.Location = new System.Drawing.Point(12223);
            
this.textBox_send.Multiline = true;
            
this.textBox_send.Name = "textBox_send";
            
this.textBox_send.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            
this.textBox_send.Size = new System.Drawing.Size(42545);
            
this.textBox_send.TabIndex = 1;
            
this.textBox_send.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtClient_KeyPress);
            
// 
            
// btnSend
            
// 
            this.btnSend.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            
this.btnSend.Enabled = false;
            
this.btnSend.Location = new System.Drawing.Point(443223);
            
this.btnSend.Name = "btnSend";
            
this.btnSend.Size = new System.Drawing.Size(4445);
            
this.btnSend.TabIndex = 2;
            
this.btnSend.Text = "发送信息";
            
this.btnSend.UseVisualStyleBackColor = true;
            
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
            
// 
            
// linkLabel_connect
            
// 
            this.linkLabel_connect.AutoSize = true;
            
this.linkLabel_connect.Location = new System.Drawing.Point(4209);
            
this.linkLabel_connect.Name = "linkLabel_connect";
            
this.linkLabel_connect.Size = new System.Drawing.Size(6713);
            
this.linkLabel_connect.TabIndex = 4;
            
this.linkLabel_connect.TabStop = true;
            
this.linkLabel_connect.Text = "连接服务器";
            
this.linkLabel_connect.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel_connect_LinkClicked);
            
// 
            
// label1
            
// 
            this.label1.AutoSize = true;
            
this.label1.Location = new System.Drawing.Point(129);
            
this.label1.Name = "label1";
            
this.label1.Size = new System.Drawing.Size(2913);
            
this.label1.TabIndex = 5;
            
this.label1.Text = "IP:";
            
// 
            
// label2
            
// 
            this.label2.AutoSize = true;
            
this.label2.Location = new System.Drawing.Point(1459);
            
this.label2.Name = "label2";
            
this.label2.Size = new System.Drawing.Size(4313);
            
this.label2.TabIndex = 7;
            
this.label2.Text = "端口:";
            
// 
            
// textBox2
            
// 
            this.textBox2.Location = new System.Drawing.Point(1946);
            
this.textBox2.Name = "textBox2";
            
this.textBox2.Size = new System.Drawing.Size(6520);
            
this.textBox2.TabIndex = 8;
            
this.textBox2.Text = "2001";
            
// 
            
// textBox1
            
// 
            this.textBox1.Location = new System.Drawing.Point(396);
            
this.textBox1.Name = "textBox1";
            
this.textBox1.Size = new System.Drawing.Size(10020);
            
this.textBox1.TabIndex = 9;
            
this.textBox1.Text = "172.21.140.142";
            
// 
            
// richTextBox_record
            
// 
            this.richTextBox_record.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        
| System.Windows.Forms.AnchorStyles.Left)
                        
| System.Windows.Forms.AnchorStyles.Right)));
            
this.richTextBox_record.BackColor = System.Drawing.SystemColors.Window;
            
this.richTextBox_record.HideSelection = false;
            
this.richTextBox_record.Location = new System.Drawing.Point(1232);
            
this.richTextBox_record.Name = "richTextBox_record";
            
this.richTextBox_record.ReadOnly = true;
            
this.richTextBox_record.Size = new System.Drawing.Size(475185);
            
this.richTextBox_record.TabIndex = 10;
            
this.richTextBox_record.Text = "";
            
// 
            
// Client
            
// 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            
this.ClientSize = new System.Drawing.Size(499288);
            
this.Controls.Add(this.richTextBox_record);
            
this.Controls.Add(this.textBox1);
            
this.Controls.Add(this.textBox2);
            
this.Controls.Add(this.label2);
            
this.Controls.Add(this.label1);
            
this.Controls.Add(this.linkLabel_connect);
            
this.Controls.Add(this.btnSend);
            
this.Controls.Add(this.textBox_send);
            
this.Name = "Client";
            
this.Text = "客户端(TcpClient)";
            
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Client_FormClosing);
            
this.ResumeLayout(false);
            
this.PerformLayout();

        }

        
#endregion

        
private System.Windows.Forms.TextBox textBox_send;
        
private System.Windows.Forms.Button btnSend;
        
private System.Windows.Forms.LinkLabel linkLabel_connect;
        
private System.Windows.Forms.Label label1;
        
private System.Windows.Forms.Label label2;
        
private System.Windows.Forms.TextBox textBox2;
        
private System.Windows.Forms.TextBox textBox1;
        
private System.Windows.Forms.RichTextBox richTextBox_record;
    }
}
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Client
{
    
public partial class Client : Form
    {
        TcpClient clientTcp;
        Thread clientThread;
        IPEndPoint serverIP;
        IPHostEntry serverPc;
        NetworkStream ns;
        
string ReceiveData = "";
        Encoding encoding 
= Encoding.UTF8;

        
public Client()
        {
            InitializeComponent();
        }

        
private void ConnectToServer()
        {
            
byte[] data = new byte[1024];
            ns 
= clientTcp.GetStream();
            serverIP 
= (IPEndPoint)clientTcp.Client.RemoteEndPoint;
            serverPc 
= Dns.GetHostEntry(serverIP.Address);
            
while (true)
            {
                
//接收服务器信息
                int bufLen = 0;
                
try
                {
                    bufLen 
= clientTcp.Available;

                    ns.Read(data, 
0, bufLen);
                    
if (bufLen == 0)
                    {
                        
continue;
                    }
                }
                
catch (Exception ex)
                {
                    MessageBox.Show(
"Receive Error:" + ex.Message);
                    
return;
                }
                ReceiveData 
= encoding.GetString(data).Substring(0, bufLen);
                ReshUI();
            }
        }

        
void ReshUI()
        {
            
//while (true)
            
//{
            
//Thread.Sleep(500);
            MethodInvoker mi = new MethodInvoker(ShowUIData);
            
this.Invoke(mi);
            
//}
        }

        
void ShowUIData()
        {
            
if (ReceiveData.Length > 0)
            {
                richTextBox_record.Text 
+= ReceiveData;
                ReceiveData 
= "";
            }
            
if (clientTcp.Connected)
                linkLabel_connect.Enabled 
= false;
            
else
                linkLabel_connect.Enabled 
= true;
            richTextBox_record.SelectionStart 
= richTextBox_record.TextLength > 0 ? richTextBox_record.TextLength - 1 : 0;
            richTextBox_record.SelectionLength 
= 0;
        }

        
string GetLocalIP()
        {
            
string strHostIP = "";
            IPHostEntry oIPHost 
= Dns.GetHostEntry(Environment.MachineName);
            
if (oIPHost.AddressList.Length > 0)
                strHostIP 
= oIPHost.AddressList[0].ToString();
            
return strHostIP;
        }


        
private void btnSend_Click(object sender, EventArgs e)
        {
            
if (textBox_send.Text.Length > 0)
            {
                
string message = string.Format("{0}{1}({2}):{3}    {4}", Environment.NewLine, Environment.UserName, DateTime.Now.ToString("HH:mm:ss"), Environment.NewLine, textBox_send.Text);
                richTextBox_record.Text 
+= message;
                richTextBox_record.SelectionStart 
= richTextBox_record.TextLength > 0 ? richTextBox_record.TextLength - 1 : 0;
                richTextBox_record.SelectionLength 
= 0;
                textBox_send.Clear();
                textBox_send.Focus();
                
//向服务器发送信息 
                byte[] data = encoding.GetBytes(message);
                ns.Write(data, 
0, data.Length);


            }
        }

        
private void linkLabel_connect_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            
//创建一个套接字
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));
            clientTcp 
= new TcpClient();

            
//将套接字与远程服务器地址相连
            try
            {
                clientTcp.Connect(ipep);
                clientThread 
= new Thread(new ThreadStart(ConnectToServer));
                clientThread.Start();
                Thread ui 
= new Thread(new ThreadStart(ReshUI));
                ui.Start();
                btnSend.Enabled 
= true;
            }
            
catch (SocketException ex)
            {
                MessageBox.Show(
"connect error: " + ex.Message);
                
return;
            }

        }

        
private void Client_FormClosing(object sender, FormClosingEventArgs e)
        {
            Environment.Exit(
0);
        }

        
private void txtClient_KeyPress(object sender, KeyPressEventArgs e)
        {
            
if (e.KeyChar == (char)Keys.Enter)
            {
                btnSend_Click(
nullnull);
                e.Handled 
= true;
            }
        }
    }
}

 


 

posted @ 2010-01-08 11:08  i_mint  阅读(383)  评论(0编辑  收藏  举报