问个Socket问题,在同一机子上打开2个客户端就出错,帮忙看下这段代码:
如果只打开一个客户端,是没有问题的,但是要是打开2个客户端,就出错了,请大侠看看下面的代码
///////////////////////----- Server 端代码 ---////////////////////
static void Main(string[] args)
{
Thread thead = null;
thead = new Thread(new ThreadStart(ListeningOper));
thead.Start();
// string s = Console.ReadLine();
}
public static void ListeningOper()
{ // 把IP地址转换为IPAddress的实例
string strIp = "127.0.0.1";
IPAddress ipAd = IPAddress.Parse(strIp);
// 初始化监听器, 端口为8001
TcpListener myList = new TcpListener(ipAd, 8001);
while (true)
{
try
{
// 开始监听服务器端口
myList.Start();
// 输出服务器启动信息
Console.WriteLine("启动端口服务...");
Console.WriteLine("本地节点为:" + myList.LocalEndpoint);
Console.WriteLine("等待连接.....");
// 等待处理接入连接请求
// 新建立的连接用套接字s表示
Socket mySocket = myList.AcceptSocket();
Console.WriteLine("连接来自 " + mySocket.RemoteEndPoint);
// 接收客户端信息
byte[] b = new byte[100];
int k = mySocket.Receive(b);
Console.WriteLine("已接收...");
UnicodeEncoding asen = new UnicodeEncoding();
string str = Encoding.Unicode.GetString(b);
Console.WriteLine("-----"+str);
mySocket.Send(asen.GetBytes("" + str));
Console.WriteLine("\n已发送回应信息");
// 释放资源 结束侦听
// mySocket.Close();
//myList.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
//Console.ReadLine();
}
}
///////////////////////-------Client 端-----////////////////////////////
static void Main(string[] args)
{
Thread thread = null;
thread = new Thread(new ThreadStart(SendOper));
thread.Start();
// SendOper();
}
static void SendOper()
{
string strIp = "127.0.0.1";
while (true)
{
try
{ // 新建客户端套接字
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("连接.....");
// 连接服务器
tcpclnt.Connect(strIp, 8001);
Console.WriteLine("已连接");
Console.Write("请输入要传输的字符串 : ");
// 读入字符串
String str = Console.ReadLine();
// 得到客户端的流
Stream stm = tcpclnt.GetStream();
// 发送字符串
UnicodeEncoding ttt = new UnicodeEncoding();
// byte[] ba = asen.GetBytes(str);
byte[] ba = ttt.GetBytes(str);
Console.WriteLine("传输中.....");
stm.Write(ba, 0, ba.Length);
// 接收从服务器返回的信息
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string str2 = Encoding.Unicode.GetString(bb);
// 输出服务器返回信息
//for (int i = 0; i < k; i++)
//{
// Console.Write(Convert.ToChar(bb[i]));
//}
Console.Write("\n 返回 :"+str2 );
// 关闭客户端连接
//tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
Console.WriteLine("\n");
}
}