本人刚学C#, 初次发帖求助,请大家不吝赐教!
代码粗陋不堪,见笑了!
1. client端简单,打开时传一个字符串(username),业务功能需要时传一个SN(不是必须),关闭时传一个值(“10”)。2. 当client端关闭时,将会通过socket发送“10”字符串给server端,但我发现开两个或两个以上的client端,关闭时出现问题,比如开两个客户端:
(1). 当先关闭后打开的client端:接受值没有异常;
(2). 当先关闭先打开的client端:server端接收到的字符串是“\0\0”,位数是对的。
(3). 当打开两个以上的client端时,要传的其他值也是这样,比如是5位的值,那接收到的就是“\0\0\0\0\0”,而不是client传的值。由于学习时间不长,考虑了很久未能想通,请大家帮忙,谢谢了!
以下是server端的代码。using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
namespace socketConn
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }        private void Form1_Load(object sender, EventArgs e)
        {
            Thread SocketThrd = new Thread(socketStart);
            SocketThrd.IsBackground = true;
            SocketThrd.Start();
        }        private byte[] data = new byte[1024];
        private Socket newsock;
        private Socket newclient;        private void socketStart()
        {
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
            newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipep);
            newsock.Listen(5);
            while (true)
            {
                newclient = newsock.Accept();
                Thread newThread = new Thread(thrdFunc);
                newThread.Start();
            }
        }        private void thrdFunc()
        {
            int recv, recv1;
            recv = newclient.Receive(data);
            userName = Encoding.ASCII.GetString(data, 0, recv);
            while (true)
            {
                try
                {
                    data = new byte[64];
                    recv1 = newclient.Receive(data);
                    switch (recv1)
                    {
                        case 2:
                            {
                                string msg = Encoding.ASCII.GetString(data, 0, recv1);
                                if (msg == "10")
                                    MessageBox.Show("OK");
                                else
                                    MessageBox.Show("Fail");
                                break;
                            }
                        default:
                            break;
                    }
                }
                catch (SocketException)
                {
                    MessageBox.Show(userName + "'s connection is abnormal\n\n      At: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm"), ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Thread.CurrentThread.Abort();
                }
            }
        }
    }
}