posts - 112, comments - 215, trackbacks - 0, articles - 34
  IT博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

C#简单网络通信程序示例

Posted on 2007-12-19 14:42 济公 阅读(1928) 评论(1)  编辑 收藏 引用 所属分类: NetWorks

//服务器端
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class server
{
 public static void Main()
 {
  try
  {
   // 把IP地址转换为IPAddress的实例
   IPAddress ipAd = IPAddress.Parse(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString());
           
   // 初始化监听器, 端口为8001
   TcpListener myList=new TcpListener(ipAd,8001);
           
   // 开始监听服务器端口
   myList.Start();

   // 输出服务器启动信息
   Console.WriteLine("在8001端口启动服务..."); 
   Console.WriteLine("本地节点为:" + myList.LocalEndpoint );
   Console.WriteLine("等待连接.....");
           
   // 等待处理接入连接请求
   // 新建立的连接用套接字s表示
   Socket s=myList.AcceptSocket();
   Console.WriteLine("连接来自 "+s.RemoteEndPoint);
           
   // 接收客户端信息
   byte[] b=new byte[100];
   int k=s.Receive(b);
   Console.WriteLine("已接收...");
   for (int i=0;i<k;i++)
   {
    Console.Write(Convert.ToChar(b[i]));
   }
           
   // 处理客户端请求,给客户端回应
   ASCIIEncoding asen=new ASCIIEncoding();
   s.Send(asen.GetBytes("The string was recieved by the server."));
   Console.WriteLine("\n已发送回应信息");
           
   // 善后工作,释放资源
   s.Close();
   myList.Stop();
  }
  catch (Exception e)
  {
   Console.WriteLine("Error..... " + e.StackTrace);
  } 
 }
}
//客户端
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;

public class client
{
 public static void Main()
 {
  try
  {
   string strHost;
   Console.WriteLine("Please enter the host IP address:");
   strHost=Console.ReadLine();
   // 新建客户端套接字
   TcpClient tcpclnt = new TcpClient();
   Console.WriteLine("连接.....");
   
   // 连接服务器
   tcpclnt.Connect(strHost,8001);
   Console.WriteLine("已连接");
   Console.Write("请输入要传输的字符串 : ");
   
   // 读入字符串
   String str=Console.ReadLine();

   // 得到客户端的流
   Stream stm = tcpclnt.GetStream();
   
   // 发送字符串
   ASCIIEncoding asen= new ASCIIEncoding();
   byte[] ba=asen.GetBytes(str);
   Console.WriteLine("传输中.....");   
   stm.Write(ba,0,ba.Length);
   
   // 接收从服务器返回的信息
   byte[] bb=new byte[100];
   int k=stm.Read(bb,0,100);
   
   // 输出服务器返回信息
   for (int i=0;i<k;i++)
   {
    Console.Write(Convert.ToChar(bb[i]));
   }
   Console.WriteLine();
   
   // 关闭客户端连接
   tcpclnt.Close();
  }  
  catch (Exception e)
  {
   Console.WriteLine("Error..... " + e.StackTrace);
  }
 }
}

Feedback

# re: C#简单网络通信程序示例  回复  更多评论   

2008-09-03 00:49 by 先锋毕业证查询
// 新建立的连接用套接字s表示
Socket s=myList.AcceptSocket();
直接套接字会出错的
只有注册用户登录后才能发表评论。