客户端与服务端之间通信。
问题比较多。
//----1----//先启动服务端,然后启动客户端。当点击客户端一连接服务端后就死了
//----2----//还有就是,接收的数据偶尔会附加上一次接收到的部分数据。//服务端
//part one
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.Sockets;
using System.Net;
using System.Reflection;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;namespace Server2
{    public partial class Server : Form
    {        private Socket socket;
        private IPAddress myIP;
        private IPEndPoint endPoint;
        private int point;
        private Socket clientSocket;
        private Assembly ass = null;
        // private System.IO.Stream stream = null;
        // private System.Media.SoundPlayer pl;
        private string txt;
        private byte[] cbs = new byte[512];
        private byte[] sbs = new byte[512];
        public Thread ThRec;
        public Thread th1;
        public Thread onFocus;
        public int send;
        public string recString;        public void frmServer()
        {
            InitializeComponent();
            ass = Assembly.GetExecutingAssembly();
            //stream = ass.GetManifestResourceStream("msgServer.msg.wav");
            // pl = new System.Media.SoundPlayer(stream);
        }        public void setItOnFocus()//发送窗口 获取焦点
        {
            rtxtSend.Focus();
        }        public Server()
        {
            InitializeComponent();
        }        private void Form1_Load(object sender, EventArgs e)//加载事件
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            cobSelectSend.SelectedIndex = 0;
            GetHostIp();
        }        private void GetHostIp()//获取本机IP
        {
            string strHostName = Dns.GetHostName(); //得到本机的主机名
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); //取得本机IP
            foreach (System.Net.IPAddress ip in ipEntry.AddressList)
            {
                txtIP.Text = ip.ToString();
                myIP = IPAddress.Parse(txtIP.Text.Trim());
            }
        }        private void btnFont_Click(object sender, EventArgs e)//字体按钮
        {
            ChooseFont();        }        private void ChooseFont()        //字体选择
        {
            FontDialog font = new FontDialog();
            font.ShowEffects = true;
            font.ShowColor = true;
            font.MinSize = 12;
            font.Font = new Font("楷体_GB2312", 18, FontStyle.Bold);
            font.Color = Color.Blue;            if (font.ShowDialog() == DialogResult.OK)
            {
                rtxtSend.Font = font.Font;
                rtxtSend.ForeColor = font.Color;
            }
        }        private void btnStart_Click(object sender, EventArgs e)//启动服务器按钮
        {
            th1 = new System.Threading.Thread(ToConnect);
            th1.Start();
        }        private void ToConnect()//启动服务
        {
            try
            {
                //myIP = IPAddress.Parse(txtIP.Text.Trim());
                point = Convert.ToInt32(txtPoint.Text.Trim());//Point
                endPoint = new IPEndPoint(myIP, point); //终端                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Bind(endPoint);//绑定
                socket.Listen(3);     //最多3人同时连接
                lblStatus.Text = "服务器已经运行,等待连接...";                clientSocket = socket.Accept();//等待接受
                //连接上时
                if (clientSocket.Connected)
                {
                    lblStatus.Text = "已经建立连接.";                    ThRec = new Thread(new ThreadStart(rec));
                    ThRec.Start();
                    ThRec.Abort();
                }
            }
            catch (SocketException)
            {
                //txtIP.Focus(); txtIP.SelectAll();
                MessageBox.Show("IP或者端口错误!");
            }
            catch (Exception e)
            {
                MessageBox.Show("Connect的Exception:" + e.ToString());
            }
        }        private void btnStop_Click(object sender, EventArgs e)//停止监听
        {
            stopSoket();
        }        private void btnSend_Click(object sender, EventArgs e)//发送消息
        {
            if (rtxtSend.Text.Trim() == "")
                return;
            else if (rtxtSend.Text.Trim().ToLower() == "clear()")
            {
                rtxtMsg.Clear();
                rtxtSend.Text = "";
                return;
            }
            else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[zoom(]+[\d]+[)]$"))
            {
                string str = rtxtSend.Text.ToLower();
                int size = Convert.ToInt32(str.Substring(str.LastIndexOf('(') + 1,
                    str.IndexOf(')') - str.LastIndexOf('(') - 1));
                rtxtMsg.Font = new Font("宋体", size, FontStyle.Bold);
                return;
            }
            else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[down(]+[\d]+[)]$"))
            {
                string str = rtxtSend.Text.ToLower();
                string size = str.Substring(str.LastIndexOf('(') + 1, str.IndexOf(')') - str.LastIndexOf('(') - 1);                if (Convert.ToInt32(size) > rtxtMsg.Text.Length)
                    return;            }
            else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[up(]+[\d]+[)]$"))
            {
                string str = rtxtSend.Text.ToLower();
                string size = str.Substring(str.LastIndexOf('(') + 1, str.IndexOf(')') - str.LastIndexOf('(') - 1);            }
            else if (rtxtSend.Text.Trim().ToLower() == "exit(0)")
            {
                this.Close();
                return;
            }            try
            {
                byte[] sbs = new byte[512];
                string user = null;
                if (txtUser.Text.Trim() == "在此输入你的名字" || txtUser.Text.Trim() == "")
                {
                    sbs = null;
                    user = "我";
                    sbs = Encoding.Unicode.GetBytes(string.Format("对方  {0}\n{1}\n", DateTime.Now.ToString(), rtxtSend.Text.Trim()));
                }
                else
                {
                    sbs = null;
                    sbs = Encoding.Unicode.GetBytes(string.Format("{0}  {1}\n{2}\n", txtUser.Text.Trim(), DateTime.Now.ToString(), rtxtSend.Text.Trim()));
                    user = txtUser.Text.Trim();
                }                clientSocket.Send(sbs, sbs.Length, 0);//发送套接字                txt = string.Format("{0}  {1}\n{2}\n", user, DateTime.Now.ToString(), rtxtSend.Text.Trim());//显示自己说的话
                int tempLen = rtxtMsg.Text.Length;
                rtxtMsg.AppendText(txt);
                rtxtMsg.Select(tempLen, txt.Length);
                rtxtMsg.SelectionFont = new Font("宋体", 10);
                rtxtMsg.SelectionColor = Color.Green;
                rtxtSend.Clear();
            }
            catch { MessageBox.Show("未建立连接,无法发送数据!"); }
        }        private void frmServer_FormClosing(object sender, FormClosingEventArgs e)//关闭窗体、进程
        {
            exitApp();
        }        private void frmServer_Load(object sender, EventArgs e)//加载事件,检测进程是否重复启动
        {
            checkAppStart();
            topWinform.Checked = true;
        }

解决方案 »

  1.   

    ThRec = new Thread(new ThreadStart(rec));
    这个rec在哪啊...
    //----2----//发送之前清空一下byte[]里面的内容在附值
      

  2.   


    ThRec.Start();
    ThRec.Abort();而且为什么刚start,就abort呢,这样你这个线程不是等于没执行么
      

  3.   

    我这个还有问题,就是你说的 byte[]里没有清空,收到的数据有不规则的重复,请指正,要不加QQ,我把代码发给你看下好么?