加入收藏 | 设为首页 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > 通讯

C#如何实现网口通讯?

时间:2024-01-26 18:05:56  来源:http://www.facechina.net  作者:admin

网口通迅啊,你的意思是通过网络和别的计算机通信吗?如果是的话那就是socket通信了,我给你个例子看看

服务器端:

try

{

int port = 2000;

string host = 176.64.158.112;

IPAddress ip = IPAddress.Parse(host);

IPEndPoint ipe = new IPEndPoint(ip, port);

s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类

s.Bind(ipe);//绑定2000端口

s.Listen(0);//开始监听

ShowMessage(Waitforconnect);

while (true)

{

Socket temp = s.Accept();//为新建连接创建新的Socket。

ShowMessage(Getaconnect from + temp); //this.Invoke(new ShowMes(ShowMessage), Getaconnect);

string recvStr = ;

byte[] recvBytes = new byte[1024];

int bytes;

bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息

recvStr = Encoding.ASCII.GetString(recvBytes, 0, bytes);

ShowMessage(String.Format(ServerGetMessage:{0}, recvStr));//this.Invoke(new ShowMes(ShowMessage), String.Format(ServerGetMessage:{0}, recvStr)); //把客户端传来的信息显示出来

string sendStr = Ok!ClientSendMessageSucessful!;

byte[] bs = Encoding.ASCII.GetBytes (sendStr);

temp.Send(bs, bs.Length, 0);//返回客户端成功信息

}

//temp.Close();

//s.Close();

}

catch (ArgumentNullException e)

{

ShowMessage(String.Format(ArgumentNullException:{0}, e));

}

catch (SocketException e)

{

ShowMessage(String.Format(SocketException:{0}, e));

}

Console.WriteLine(PressEntertoExit);

客户端:

try

{

Socket c;

int port = 2000;

string host = 176.64.158.112;

IPAddress ip = IPAddress.Parse(host);

IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例

c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket

ShowMessage(Conneting...);

c.Connect(ipe);//连接到服务器

string sendStr = hello!This is a socket test;

byte[] bs = Encoding.ASCII.GetBytes(sendStr);

ShowMessage(SendMessage);

c.Send(bs, bs.Length, 0);//发送测试信息

string recvStr = ;

byte[] recvBytes = new byte[1024];

int bytes;

bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息

if (bytes <= 0)

break;

recvStr = Encoding.ASCII.GetString(recvBytes, 0, bytes);

ShowMessage(String.Format(ClientGetMessage:{0}, recvStr));//显示服务器返回信息

sendStr = hello!This is a socket test;

bs = Encoding.ASCII.GetBytes(sendStr);

ShowMessage(SendMessage);

c.Send(bs, bs.Length, 0);//发送测试信息

Thread.Sleep(100);

c.Close();

}

catch (ArgumentNullException e)

{

ShowMessage(String.Format(ArgumentNullException:{0}, e));

}

catch (SocketException e)

{

ShowMessage(String.Format(SocketException:{0}, e));

}

ShowMessage(String.Format(PressEntertoExit));

来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
相关文章
    无相关信息
栏目更新
栏目热门