日期:2014-05-17  浏览次数:20744 次

关于c#的socket,客户端发消息,服务端只接收一次的问题.
本帖最后由 wenyu_825 于 2014-01-14 14:59:57 编辑

//服务端代码
using ServerDemo.roc.socket_package;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServerDemo.windows_package
{
    public partial class WindowMain : Form
    {
        private Socket socket = null;
        public WindowMain()
        {
            InitializeComponent();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            Thread threadListen = new Thread(new ThreadStart(listen));
            threadListen.IsBackground = true;
            threadListen.Start();
            
        }
        private void listen()
        {
            Console.WriteLine("Start Listening ...");
            appendtextBoxLog("Start Listening ...");
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //基于TCP/IP的网络上通讯;
            //Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //基于UDP的网络上通讯;
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, 6666));//设定该套接字的绑定IP,接受从任意IP地址发往端口6666的消息;//如果需要限制IP,就把IPAddress.Any改一下;
            serverSocket.Listen(1000);//将套接字设置为监听状态,并设置监听队列为100;//解释:如果1秒内有N多人并发访问可能暂时要存在队列里,估计1秒内几千人访问,设置100就足够用了.
            while (true)//死循环,即不发生异常中断的情况下一直接受消息 
            {
                this.socket = serverSocket.Accept();//(4)Create a new Socket for a newly created connection  
                appendtextBoxLog(this.socket.RemoteEndPoint.ToString()+" 连接成功");
                Thread thread = new Thread(new ThreadStart(start));
 &nb