C#如何实现网口通讯?

 我来答
Ray01
推荐于2019-08-14 · TA获得超过464个赞
知道小有建树答主
回答量:312
采纳率:0%
帮助的人:293万
展开全部
网口通迅啊,你的意思是通过网络和别的计算机通信吗?如果是的话那就是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"));
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式