您的位置:首页 > 编程语言 > C#

简单的C#socket例子(转载)

2012-11-14 16:49 190 查看
打开命名空间

using System.Net;
using System.Net.Sockets;

服务端代码:



static void Main(string[] args)
{
int port = 2000;
string host = "127.0.0.1";

IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipe);
socket.Listen(0);  //监听
Console.WriteLine("waiting.......");

//接受来自客户端发送的信息
Socket temp = socket.Accept();  //创建新的socket用于和客户端通信
Console.WriteLine("ok...");
string recstr = "";
byte[] recbyte = new byte[1024];
int bytes;
bytes = temp.Receive(recbyte, recbyte.Length, 0);
recstr += Encoding.ASCII.GetString(recbyte, 0, bytes);

//给客户端返回信息
Console.WriteLine("server get message:{0}", recstr);
string sendstr = "client send message successful";
byte[] by = Encoding.ASCII.GetBytes(sendstr);
temp.Send(by, by.Length, 0);  //发送
temp.Close();                 //关闭
socket.Close();
Console.ReadLine();

}




客户端代码:



static void Main(string[] args)
{
try
{
int port = 2000;
string host = "127.0.0.1";

IPAddress ip = IPAddress.Parse(host);
IPEndPoint iped = new IPEndPoint(ip, port);

Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("waiting......");
soc.Connect(iped);  //连接

//向服务端发送消息
string sendstr = "hello,this is client message";
byte[] bytes = Encoding.ASCII.GetBytes(sendstr);
Console.WriteLine("send message");
soc.Send(bytes);

//接受由服务端返回的信息
string recstr = "";
byte[] recbyte = new byte[1024];
int bytess;
bytess = soc.Receive(recbyte, recbyte.Length, 0);
recstr += Encoding.ASCII.GetString(recbyte, 0, bytess);
Console.WriteLine("get message:{0}", recstr);
soc.Close();

}
catch (Exception ex)
{
Console.WriteLine("error");
}
Console.WriteLine("press enter exit");
Console.ReadLine();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: