多线程Socket编程,程序走到socket.Accept()就不继续向下运行了

游荡的風 2014-04-06 07:37:21
服务器端==========================================
主界面新建线程:
Thread ScreenSendThread = new Thread(new ThreadStart(ScreenSend));
ScreenSendThread.Start();

ScreenSend函数:
        private void ScreenSend()
{
IPAddress ServerIp = GetServerIP();
ScreenIep = new IPEndPoint(ServerIp, 9999);
ScreenSendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ScreenSendSocket.Bind(ScreenIep);
ScreenSendSocket.Listen(10);
ScreenSocket = socket.Accept();//这里,每当调试到这儿都无法进行下去

System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Interval = 1000;
tmr.Elapsed += new ElapsedEventHandler(tmr_ScreenSend);

while (true)
{
if (command == "00")
{
tmr.Start();
}
else
{
tmr.Stop();
}
}
}

void tmr_ScreenSend(object sender, ElapsedEventArgs e)
{
ScreenMonitor();
ScreenSocket.Send(bytePicture);
}

客户端=================================
        private void ScreenReceive()
{

int ServerPort = 9999;
this.Text = _ip.ip;

IPAddress ServerIP = IPAddress.Parse(_ip.ip);

IPEndPoint ScreenIep = new IPEndPoint(ServerIP, ServerPort);
ScreenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Thread.Sleep(2000);
ScreenSocket.Connect(ScreenIep);

while (true)
{
try
{
byte[] bytePicture = new byte[300 * 1024];
ScreenSocket.Receive(bytePicture);

MemoryStream ms = new MemoryStream(bytePicture);
Image bm = Image.FromStream(ms);
ms.Close();

pictureBox1.Image = bm;
}
catch { }
}
}
...全文
491 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 3 楼 YouDown 的回复:
[quote=引用 2 楼 sp1234 的回复:] 如果不想阻塞,应该使用 BeginAccept。
我是想用阻塞,等客户端连接成功再传数据。 可我已经开启了客户端,它还在阻塞着。 调试的时候 客户端ScreenSocket.Connect(ScreenIep);通过了,也就是说明连接成功,但是客户端又在ScreenSocket.Receive(bytePicture);这里阻塞了。[/quote] 此时你的服务器还在 ScreenSocket = socket.Accept(); 这条语句上阻塞着吗? 跟你了解调试过程,比较费劲。你总是不描述重要的东西,而贴一大堆其它的东西。
hanhualangzi 2014-04-07
  • 打赏
  • 举报
回复
服务端:

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace tcpserver
{
    class server
    {
        static void Main(string[] args)
        {
            #region    //TCP协议通信
            int recv;     //客户端发送信息长度
            byte[] data;  //缓存客户端发送的信息,sockets传递的信息必须为字节数组
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);   //本机预使用的IP和端口
            
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
            newsock.Bind(ipep);     //绑定
            newsock.Listen(10);     //监听

            Console.WriteLine("waiting for a client......");

            Socket client = newsock.Accept();   //有客户连接尝试时执行,并返回一个新的socket,用于与客户之间通信
            IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("connect with client " + clientip.Address + " at port " + clientip.Port);

            string welcom = "welcom here!";
            data = Encoding.ASCII.GetBytes(welcom);

            client.Send(data, data.Length, SocketFlags.None);   //发消息

            while (true)   //死循环不断从客户端获取信息
            {
                data = new byte[1024];
                recv = client.Receive(data);
                Console.WriteLine("recv = " + recv);

                if (recv == 0) break;     //信息长度为0,说明客户端断开

                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                client.Send(data, recv, SocketFlags.None);

                //在服务器端输入,发送到客户端
                //string input = Console.ReadLine();
                //if (input == "exit") break;
                //client.Send(Encoding.ASCII.GetBytes(input));
                //data = new byte[1024];
                //recv = client.Receive(data);
                //input = Encoding.ASCII.GetString(data, 0, recv);
                //Console.WriteLine(input);
            }

            Console.WriteLine("Disconnect from " + clientip.Address);
            client.Close();
            newsock.Close();
            #endregion
        }
    }
}

 

客户端:

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace tcpclient
{
    class client
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            newclient.Bind(new IPEndPoint(IPAddress.Any, 905));
            
            Console.WriteLine("please input the server ip:");
            string ipadd = Console.ReadLine();
            Console.WriteLine();
            Console.WriteLine("please input the server port:");
            int port = Convert.ToInt32(Console.ReadLine());

            IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);   //服务器IP和端口
            
            try
            {
                newclient.Connect(ie);   //客户端想特定的服务器发送信息,所以不需要绑定本机的IP和端口
            }
            catch(SocketException e)
            {
                Console.WriteLine("unable to connect to server");
                Console.WriteLine(e.Message);
                return;
            }

            int receivedDataLebgth = newclient.Receive(data);
            string stringdata = Encoding.ASCII.GetString(data, 0, receivedDataLebgth);
            Console.WriteLine(stringdata);

            while (true)
            {
                string input = Console.ReadLine();
                if (input == "exit") break;

                newclient.Send(Encoding.ASCII.GetBytes(input));
                data = new byte[1024];
                receivedDataLebgth = newclient.Receive(data);
                stringdata = Encoding.ASCII.GetString(data, 0, receivedDataLebgth);
                Console.WriteLine(stringdata);
            }

            Console.WriteLine("disconnect from server");
            newclient.Shutdown(SocketShutdown.Both);

            newclient.Close();
        }
    }
}
我昨天刚学习了这个,完全可以啊. http://blog.csdn.net/nanwang314/article/details/6205369
游荡的風 2014-04-07
  • 打赏
  • 举报
回复
引用 8 楼 hanhualangzi 的回复:
服务端:

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace tcpserver
{
    class server
    {
        static void Main(string[] args)
        {
            #region    //TCP协议通信
            int recv;     //客户端发送信息长度
            byte[] data;  //缓存客户端发送的信息,sockets传递的信息必须为字节数组
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);   //本机预使用的IP和端口
            
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
            newsock.Bind(ipep);     //绑定
            newsock.Listen(10);     //监听

            Console.WriteLine("waiting for a client......");

            Socket client = newsock.Accept();   //有客户连接尝试时执行,并返回一个新的socket,用于与客户之间通信
            IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("connect with client " + clientip.Address + " at port " + clientip.Port);

            string welcom = "welcom here!";
            data = Encoding.ASCII.GetBytes(welcom);

            client.Send(data, data.Length, SocketFlags.None);   //发消息

            while (true)   //死循环不断从客户端获取信息
            {
                data = new byte[1024];
                recv = client.Receive(data);
                Console.WriteLine("recv = " + recv);

                if (recv == 0) break;     //信息长度为0,说明客户端断开

                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                client.Send(data, recv, SocketFlags.None);

                //在服务器端输入,发送到客户端
                //string input = Console.ReadLine();
                //if (input == "exit") break;
                //client.Send(Encoding.ASCII.GetBytes(input));
                //data = new byte[1024];
                //recv = client.Receive(data);
                //input = Encoding.ASCII.GetString(data, 0, recv);
                //Console.WriteLine(input);
            }

            Console.WriteLine("Disconnect from " + clientip.Address);
            client.Close();
            newsock.Close();
            #endregion
        }
    }
}

 

客户端:

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace tcpclient
{
    class client
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            newclient.Bind(new IPEndPoint(IPAddress.Any, 905));
            
            Console.WriteLine("please input the server ip:");
            string ipadd = Console.ReadLine();
            Console.WriteLine();
            Console.WriteLine("please input the server port:");
            int port = Convert.ToInt32(Console.ReadLine());

            IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);   //服务器IP和端口
            
            try
            {
                newclient.Connect(ie);   //客户端想特定的服务器发送信息,所以不需要绑定本机的IP和端口
            }
            catch(SocketException e)
            {
                Console.WriteLine("unable to connect to server");
                Console.WriteLine(e.Message);
                return;
            }

            int receivedDataLebgth = newclient.Receive(data);
            string stringdata = Encoding.ASCII.GetString(data, 0, receivedDataLebgth);
            Console.WriteLine(stringdata);

            while (true)
            {
                string input = Console.ReadLine();
                if (input == "exit") break;

                newclient.Send(Encoding.ASCII.GetBytes(input));
                data = new byte[1024];
                receivedDataLebgth = newclient.Receive(data);
                stringdata = Encoding.ASCII.GetString(data, 0, receivedDataLebgth);
                Console.WriteLine(stringdata);
            }

            Console.WriteLine("disconnect from server");
            newclient.Shutdown(SocketShutdown.Both);

            newclient.Close();
        }
    }
}
我昨天刚学习了这个,完全可以啊. http://blog.csdn.net/nanwang314/article/details/6205369
是我写代码马虎了 这个没问题的说~
游荡的風 2014-04-07
  • 打赏
  • 举报
回复
引用 7 楼 lym11023 的回复:
楼主,Socket类通讯,可以参照以下文章: http://blog.csdn.net/lym11023/article/details/15502909
谢谢~ 看过这篇文章~
游荡的風 2014-04-07
  • 打赏
  • 举报
回复
引用 9 楼 sp1234 的回复:
[quote=引用 3 楼 YouDown 的回复:] [quote=引用 2 楼 sp1234 的回复:] 如果不想阻塞,应该使用 BeginAccept。
我是想用阻塞,等客户端连接成功再传数据。 可我已经开启了客户端,它还在阻塞着。 调试的时候 客户端ScreenSocket.Connect(ScreenIep);通过了,也就是说明连接成功,但是客户端又在ScreenSocket.Receive(bytePicture);这里阻塞了。[/quote] 此时你的服务器还在 ScreenSocket = socket.Accept(); 这条语句上阻塞着吗? 跟你了解调试过程,比较费劲。你总是不描述重要的东西,而贴一大堆其它的东西。[/quote] 找到原因了 是写代码马虎了。 ScreenSocket = socket.Accept(); 这句是错的 应该是 ScreenSocket = ScreenSendSocket.Accept();
  • 打赏
  • 举报
回复
楼主,Socket类通讯,可以参照以下文章: http://blog.csdn.net/lym11023/article/details/15502909
游荡的風 2014-04-06
  • 打赏
  • 举报
回复
引用 5 楼 hanhualangzi 的回复:
       Socket newClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newClient.Bind(new IPEndPoint(IPAddress.Any, 5600));
            IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
            newClient.Connect(ie); 
不可以啊~这样改过之后客户端连接不上服务器了
hanhualangzi 2014-04-06
  • 打赏
  • 举报
回复
       Socket newClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newClient.Bind(new IPEndPoint(IPAddress.Any, 5600));
            IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
            newClient.Connect(ie); 
游荡的風 2014-04-06
  • 打赏
  • 举报
回复
有没有知道的
游荡的風 2014-04-06
  • 打赏
  • 举报
回复
引用 2 楼 sp1234 的回复:
如果不想阻塞,应该使用 BeginAccept。
我是想用阻塞,等客户端连接成功再传数据。 可我已经开启了客户端,它还在阻塞着。 调试的时候 客户端ScreenSocket.Connect(ScreenIep);通过了,也就是说明连接成功,但是客户端又在ScreenSocket.Receive(bytePicture);这里阻塞了。
  • 打赏
  • 举报
回复
如果不想阻塞,应该使用 BeginAccept。
  • 打赏
  • 举报
回复
Accept是阻塞线程的语句,等着你的客户端访问呢。

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧