使用Socket编写服务端和客户端
服务端
const int PORT = 6602;
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
IPEndPoint ep = new IPEndPoint(ip, PORT);
listener.Bind(ep);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for connection on port 6602");
Socket socket = listener.Accept();
string rec = string.Empty;
while (true)//接收字符串
{
byte[] recBytes = new byte[1024];
int numBytes = socket.Receive(recBytes);
Console.WriteLine("Receiving...");
rec += Encoding.UTF8.GetString(recBytes, 0, numBytes);
if (rec.IndexOf("[END]") != -1) break;
}
Console.WriteLine("Received string: {0}", rec); //rec是收到的字符串
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
客户端 已经写成了一个函数方便重复使用
///
/// 通过socket发送信息
///
/// 要发送的字符串
/// IP地址
/// 端口
private static void socketSendMessage(string sendMsg, string stringIP, int port)
{
byte[] recBytes = new byte[1024];
IPHostEntry iphost = Dns.GetHostEntry(stringIP);
IPAddress[] ipaddresses = iphost.AddressList;
IPAddress ipaddress = ipaddresses[0];
foreach (IPAddress i in ipaddresses)
{
if (i.AddressFamily == AddressFamily.InterNetwork)
{
ipaddress = i;
break;
}
}
IPEndPoint ipendpoint = new IPEndPoint(ipaddress, port);
Console.WriteLine("Starting...");
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, Type.Tcp);
sender.Connect(ipendpoint);
Console.WriteLine("Connected to {0}", sender.RemoteEndPoint);
Console.WriteLine("Msg is {0}", sendMsg);
byte[] sendMsgByte = Encoding.UTF8.GetBytes(sendMsg + "[END]");
sender.Send(sendMsgByte);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadKey();
}
posted @
2014-02-07 21:19
fuis
阅读(
446)
评论()
收藏
举报