服务器端通讯程序问题请教高手

zjut_yanyehe 2012-03-26 12:13:12
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);
}
}
}
}
...全文
133 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
d4320653n 2012-03-26
  • 打赏
  • 举报
回复
在此句中添加try{}catch{}语句,得出错误代码再分析
zjut_yanyehe 2012-03-26
  • 打赏
  • 举报
回复
c.Connect(ipe);//连接到服务器
这句调试的时候说有问题啊!请教高手
zjut_yanyehe 2012-03-26
  • 打赏
  • 举报
回复
我试过但是会影响代码的运行速度啊 !!!很郁闷啊
d4320653n 2012-03-26
  • 打赏
  • 举报
回复
你现在在调试阶段,先把问题解决。再说就算实用你也需要用try,catch。否则若连接错误则系统会卡死

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧