C Sharp/網絡編程
外觀
< C Sharp
伺服器端
[編輯]IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(30);
while (true)
{
Socket sock = listener.Accept();
byte[] bs = new byte[1024*1024];
int ilen = sock.Receive(bs);
}
客戶端
[編輯]IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), iPort);//IP和端口
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(ipep);
sock.Send(Sendbytes, Sendbytes.Length, SocketFlags.None);//发送信息
基於TcpListener的伺服器端
[編輯]TcpListener listener = new TcpListener(IP, 1234);
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();//接受一个Client
byte[] buffer = new byte[client.ReceiveBufferSize];
NetworkStream stream = client.GetStream();//获取网络流
stream.Read(buffer, 0, buffer.Length);//读取网络流中的数据
stream.Close();//关闭流
client.Close();//关闭Client
receiveString = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串
Console.WriteLine(receiveString);
}
listener.Stop();
基於TcpClient的伺服器端
[編輯]TcpClient client = new TcpClient(ip, 1234);
NetworkStream sendStream = client.GetStream();
Byte[] sendBytes = Encoding.Default.GetBytes(msg);
sendStream.Write(sendBytes, 0, sendBytes.Length);
sendStream.Flush();
sendStream.Close();//关闭网络流 client.Close();//关闭客户端
異步方式
[編輯]public static ManualResetEvent allDone = new ManualResetEvent(false);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(30);
while (true)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
allDone.WaitOne();
}
public static void AcceptCallback(IAsyncResult ar)
{
try
{
if (IsListening)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.headbuffer, 0, StateObject.HeadBufferSize, 0,
new AsyncCallback(ReceiveHead), state);
}
}
catch (System.Exception ex)
{
log.ErrorFormat("AcceptCallback异常,原因:{0}", ex.Message);
}
}
private static void ReceiveHead(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
uint length = ByteTouint(state.headbuffer, 3, 4);
state.length = (int)length - state.headbuffer.Length;
state.bodybuffer = new byte[length - state.headbuffer.Length];
handler.BeginReceive(state.bodybuffer, 0, state.bodybuffer.Length, 0,
new AsyncCallback(ReadCallback), state);
}
catch (System.Exception ex)
{
log.ErrorFormat("ReceiveHead异常,原因:{0}", ex.Message + ex.StackTrace);
}
}
public static void ReadCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
//接收的字节在state.bodybuffer里,下面开始处理
}
public class StateObject
{
public Socket workSocket = null;
public const int HeadBufferSize = 7;
public byte[] headbuffer = new byte[HeadBufferSize];
public byte[] bodybuffer;
public int length;
}