C#建立套接字 问题

来源:百度知道 编辑:UC知道 时间:2024/06/13 19:33:31
很简单的东西,
服务器开启
然后客户端连上服务器 说一句话(比如 你好我是客户端)
然后服务器上显示:客户端说 你好我是客户端
服务器可以回一句话给客户端 你好我是服务器
客户端显示 服务器说 你好我是服务器

C#的套接字不是很熟 我看很多书上写的用BYTE []传 文字
能用stream 流传吗?
请给我代码 能运行的。。

using System;
  using System.Collections.Generic;
  using System.Text;
  using System.Net;
  using System.Net.Sockets;

  namespace SocketCli
  {
  class Program
  {
  [STAThread]
  static void Main(string[] args)
  {
  //
  // TODO: 在此处添加代码以启动应用程序
  //
  byte[] data = new byte[1024];
  Socket newclient=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  //Console.Write("请输入服务器");
  //string ipadd=Console.ReadLine();
  //Console.WriteLine();
  //Console.Write("please input the server port:");
  //int port=Convert.ToInt32(Console.ReadLine());
  IPEndPoint ie=new IPEndPoint(IPAddress.Parse("192.168.1.2"),9050);//服务器的IP和端口
  try
  {
  //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
  newclient.Connect(ie);
  }
  catch(SocketException e)
  {
  Console.WriteLine("未连接服务器");<