c# 彩笔向大家请教一个多线程socket 问题
使用CMD telnet 登陆到 多线程服务端程序发生异常,描述如下 : 在执行此操作前必须先调用 Listen 方法
代码如下:
using System;
using
using
using System.Text;
using System.Threading;
namespace socket_demo2
{
class Server
{
Thread thread;
ServerThread serverThread;
Socket socket;
IPAddress ip;
IPEndPoint ipep;
byte[] byteMessage;
public Server()
{
Console.WriteLine("Server...............");
init();
}
public void init()
{
ip = IPAddress.Parse("127.0.0.1");
ipep = new IPEndPoint(ip,12);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipep);
socket.Listen(5);
Console.WriteLine("listen...............");
Console.WriteLine("Wait for connect");
thread = new Thread(new ThreadStart(this.accept));
thread.Start();
}
public void accept()
{
while (true)
{
socket = socket.Accept();
Console.WriteLine("accept..............." + socket.RemoteEndPoint.ToString());
serverThread = new ServerThread(socket);
}
}
static void Main(string[] args)
{
Server s = new Server();
}
}
}
using System;
using
using
using System.Text;
using System.Threading;
namespace socket_demo2
{
class ServerThread
{
Thread thread;
Socket socket;
byte[] byteMessage = new byte[1024];
public ServerThread()
{
}
public ServerThread(Socket socket)
{
Console.WriteLine("ServerThread init ............. ");
this.socket = socket;
thread = new Thread(new ThreadStart(this.run));
thread.Start();
}
public void run()
{
Console.WriteLine("ServerThread run ............. ");
socket.Receive(byteMessage);
string time = DateTime.Now.ToShortTimeString();
string msg = time + ":" + "Message from:";
msg += socket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage);
Console.WriteLine(msg + "\n");
this.socket.SendTo(Encoding.ASCII.GetBytes(msg), this.socket.RemoteEndPoint);
}
}
}
麻烦各位哥帮忙看一下