以下是我参考文档凑起来的程序, 但是client一链接server, server就终止了, client也产生了异常,
恳请大虾们有空的时候帮忙look look~~ 感激不尽!!! 谢谢!////////////////////////////////////////// sever
using System;
using System.Collections.Generic;
using System.Text;using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;namespace TcpServer
{
class Program
{
// start
static void Main(string[] args)
{
Console.Title = "server";
new Program().service();
} // Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize]; // max connection count
static int MAX_CLIENT = 5; // server
TcpListener listener;
// List of connect clients.
private List<TcpClient> mClients; // Thread signal.
public static ManualResetEvent tcpClientConnected = new ManualResetEvent(false);
public void service()
{
mClients = new List<TcpClient>(); // Set the event to nonsignaled state.
tcpClientConnected.Reset(); listener = new TcpListener(getIP(), 9999);
//listener = new TcpListener(9999); listener.Start();
listener.BeginAcceptTcpClient(new AsyncCallback(onClientConnected), listener); // Wait until a connection is made and processed before
// continuing.
tcpClientConnected.WaitOne(); } public void onClientConnected(IAsyncResult ia)
{
try
{
TcpListener ls = (TcpListener)ia.AsyncState;
Console.WriteLine("New Connection!"); if (mClients.Count >= MAX_CLIENT)
{
Console.WriteLine("Reach Max Connection!");
ls.EndAcceptTcpClient(ia);
return;
} TcpClient client = ls.EndAcceptTcpClient(ia); lock (mClients)
{
mClients.Add(client);
} // Signal the calling thread to continue.
tcpClientConnected.Set(); Console.WriteLine("Client {0} Connected.", client.Client.RemoteEndPoint); client.GetStream().BeginRead(buffer, 0, BufferSize, new AsyncCallback(onRead), client);
listener.BeginAcceptTcpClient(new AsyncCallback(onClientConnected), listener);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
} }
public void onRead(IAsyncResult ia)
{
TcpClient client = (TcpClient)ia.AsyncState;
int readCount = client.GetStream().EndRead(ia);
string content = string.Empty; //if(readCount > 0)
//{
content = Encoding.ASCII.GetString(buffer);
Console.WriteLine("Client {0} Said: {1}", client.Client.RemoteEndPoint, content);
if(content.IndexOf("goodbye") > -1){
Send(client, "GoodBye!");
client.Close();
}else
{
// continue reading
client.GetStream().BeginRead(buffer, 0, BufferSize, new AsyncCallback(onRead), client);
}
//}
} private static void Send(TcpClient c, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device.
c.GetStream().BeginWrite(byteData, 0, byteData.Length, new AsyncCallback(onSend), c);
}
private static void onSend(IAsyncResult ar)
{
try
{
TcpClient client = (TcpClient)ar.AsyncState; // Complete sending the data to the remote device.
client.GetStream().EndWrite(ar);
//Console.WriteLine("Sent {0} bytes to client.", bytesSent);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public IPAddress getIP()
{
IPHostEntry entry = Dns.GetHostByName(Dns.GetHostName());
IPAddress address = entry.AddressList[0];
return address;
}
}
}
恳请大虾们有空的时候帮忙look look~~ 感激不尽!!! 谢谢!////////////////////////////////////////// sever
using System;
using System.Collections.Generic;
using System.Text;using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;namespace TcpServer
{
class Program
{
// start
static void Main(string[] args)
{
Console.Title = "server";
new Program().service();
} // Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize]; // max connection count
static int MAX_CLIENT = 5; // server
TcpListener listener;
// List of connect clients.
private List<TcpClient> mClients; // Thread signal.
public static ManualResetEvent tcpClientConnected = new ManualResetEvent(false);
public void service()
{
mClients = new List<TcpClient>(); // Set the event to nonsignaled state.
tcpClientConnected.Reset(); listener = new TcpListener(getIP(), 9999);
//listener = new TcpListener(9999); listener.Start();
listener.BeginAcceptTcpClient(new AsyncCallback(onClientConnected), listener); // Wait until a connection is made and processed before
// continuing.
tcpClientConnected.WaitOne(); } public void onClientConnected(IAsyncResult ia)
{
try
{
TcpListener ls = (TcpListener)ia.AsyncState;
Console.WriteLine("New Connection!"); if (mClients.Count >= MAX_CLIENT)
{
Console.WriteLine("Reach Max Connection!");
ls.EndAcceptTcpClient(ia);
return;
} TcpClient client = ls.EndAcceptTcpClient(ia); lock (mClients)
{
mClients.Add(client);
} // Signal the calling thread to continue.
tcpClientConnected.Set(); Console.WriteLine("Client {0} Connected.", client.Client.RemoteEndPoint); client.GetStream().BeginRead(buffer, 0, BufferSize, new AsyncCallback(onRead), client);
listener.BeginAcceptTcpClient(new AsyncCallback(onClientConnected), listener);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
} }
public void onRead(IAsyncResult ia)
{
TcpClient client = (TcpClient)ia.AsyncState;
int readCount = client.GetStream().EndRead(ia);
string content = string.Empty; //if(readCount > 0)
//{
content = Encoding.ASCII.GetString(buffer);
Console.WriteLine("Client {0} Said: {1}", client.Client.RemoteEndPoint, content);
if(content.IndexOf("goodbye") > -1){
Send(client, "GoodBye!");
client.Close();
}else
{
// continue reading
client.GetStream().BeginRead(buffer, 0, BufferSize, new AsyncCallback(onRead), client);
}
//}
} private static void Send(TcpClient c, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device.
c.GetStream().BeginWrite(byteData, 0, byteData.Length, new AsyncCallback(onSend), c);
}
private static void onSend(IAsyncResult ar)
{
try
{
TcpClient client = (TcpClient)ar.AsyncState; // Complete sending the data to the remote device.
client.GetStream().EndWrite(ar);
//Console.WriteLine("Sent {0} bytes to client.", bytesSent);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public IPAddress getIP()
{
IPHostEntry entry = Dns.GetHostByName(Dns.GetHostName());
IPAddress address = entry.AddressList[0];
return address;
}
}
}
using System.Collections.Generic;
using System.Text;using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;namespace TcpClienter
{
class Program
{ // start
static void Main(string[] args)
{
Console.Title = "client";
new Program().start();
}
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize]; TcpClient client; public void start()
{
try
{
client = new TcpClient(getIP().ToString(), 9999);
//client.Connect(getIP(), 9999); client.GetStream().BeginRead(buffer, 0, BufferSize, new AsyncCallback(onRead), client); Stream s = client.GetStream();
StreamReader sr = new StreamReader(s);
while (true)
{
Console.Write("Message: ");
string msg = Console.ReadLine();
// begin write
Send(client, msg);
}
s.Close();
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
finally
{
client.Close();
}
} public void onRead(IAsyncResult ia)
{
TcpClient client = (TcpClient)ia.AsyncState;
int readCount = client.GetStream().EndRead(ia);
string content = string.Empty; //if (readCount > 0)
//{
content = Encoding.ASCII.GetString(buffer);
Console.WriteLine("Client {0} Said: {1}", client.Client.RemoteEndPoint, content);
if (content.IndexOf("goodbye") > -1)
{
Send(client, "GoodBye!");
client.Close();
}
else
{
// continue reading
client.GetStream().BeginRead(buffer, 0, BufferSize, new AsyncCallback(onRead), client);
}
//}
}
private void Send(TcpClient c, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device.
c.GetStream().BeginWrite(byteData, 0, byteData.Length, new AsyncCallback(onSend), c);
}
private static void onSend(IAsyncResult ar)
{
try
{
TcpClient client = (TcpClient)ar.AsyncState; // Complete sending the data to the remote device.
client.GetStream().EndWrite(ar);
//Console.WriteLine("Sent {0} bytes to client.", client.GetStream().);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
} public static IPAddress getIP()
{
IPHostEntry entry = Dns.GetHostByName(Dns.GetHostName());
IPAddress address = entry.AddressList[0];
return address;
}
}
}
------------------------------------------请问如何死锁了? 谢谢!!!
listener.BeginAcceptTcpClient(new AsyncCallback(onClientConnected), listener);TcpListener有BeginAcceptTcpClient()这个方法吗?Visual studio 2003是没有的,楼主用的是2005版?
所有BeginRead都是指向同一个buffer会有线程安问题,会导致接收数据错误.
方法是不是应该加个循环,要不接收第一个请求后程序就结束了.
相关的连接都关闭,由于连接关闭客户端的Socket也会发生错误.