日期:2014-05-18  浏览次数:20842 次

服务器端通讯程序问题请教高手
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication2
{
  class Program
  {
  static void Main(string[] args)
  {
  try
  {
  //设置IP和端口号
  int port = 2200;
  string host = "192.168.137.98";
  //创建终节点EndPoint
  IPAddress ip = IPAddress.Parse(host);
  IPEndPoint ipe = new IPEndPoint(ip, port);//把IP和端口转化为IPEndPoint实例
  //创建Socket并连接到服务器
  Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  Console.WriteLine("服务器正在连接中.....");
  c.Connect(ipe);//连接到服务器
  //向服务器发送消息
  Encoding myEncoding=Encoding.GetEncoding("GB2312");
  //中文代码
  string senderstring ="打声招呼,这是服务器发送的测试信息,";
  byte[] bs =myEncoding.GetBytes(senderstring.ToCharArray());//把字符串编码为字符
  Console.WriteLine("开始发送消息");
  c.Send(bs,bs.Length,0);//发送消息 //接受从服务器返回的消息
  string recivestring ="";
  byte[] reciveBytes=new byte [1024];
  int bytes;
  bytes=c.Receive(reciveBytes,reciveBytes.Length,0);
  //从服务器端返回消息
  recivestring +=myEncoding.GetString(reciveBytes,0,bytes);
  Console.WriteLine("服务器端返回的信息:\n{0}",recivestring);//显示器返回信息
  c .Close();
  }
  catch(ArgumentNullException e)
  {
  Console.WriteLine("argumentNullException:{0}",e);
  }
  catch(SocketException e)
  {
  Console.WriteLine("SocketException:{0}",e);
  }
  }
  }
}


------解决方案--------------------
在此句中添加try{}catch{}语句,得出错误代码再分析
------解决方案--------------------
你现在在调试阶段,先把问题解决。再说就算实用你也需要用try,catch。否则若连接错误则系统会卡死