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

socket编程 不是很难 问题解决立即结分~
为了实现服务器与多个客户机通信 但是现在问题是每个客户机只能发送一次信息 到第二次发送的时候就不行了 而且在显示方面也又问题但不知道是哪里出错了 找了半天妹看出来 麻烦那个老大帮我看下 感激涕零~
[code=C#][/code]
//客户机代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TcpClient
{
  public class TcpClientService
  {
  public string message;
  public byte[] buffer=new byte[1024];
  public TcpClientService()
  { 
  Socket clientService=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  IPAddress address=IPAddress.Parse("127.0.0.1");
  IPEndPoint IPEP=new IPEndPoint(address,13000);
  clientService.Connect(IPEP);
  //if (clientService.Connected)
  //{
  Console.WriteLine("连接已建立.......");
  while (true)
  {
  Console.Write("请输入要传输的信息");
  message = Console.ReadLine();
  if (message == "exit")
  {
  break;
  }
  else
  {
  buffer = Encoding.ASCII.GetBytes(message);
  clientService.Send(buffer);
  int i = clientService.Receive(buffer);
  message = Encoding.ASCII.GetString(buffer, 0, i);
  Console.WriteLine("收到回复信息:{0}", message);
  }
  }
  clientService.Close();
  Console.WriteLine("连接断开");
  //}
  }
  public static void Main()
  {
  TcpClientService Tcp = new TcpClientService();
  }
  }
}
[code=C#][/code]
//服务器代码
namespace TcpService
{
  public class TcpServiceServer
  {
  public Socket service;
  public TcpServiceServer()
  {
  Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  IPAddress address = IPAddress.Parse("127.0.0.1");
  IPEndPoint IPEP = new IPEndPoint(address, 13000);
  socket.Bind(IPEP);
  socket.Listen(20);
  Console.WriteLine("等待客户机连接......");
  while (true)
  {
  service = socket.Accept();
  TcpService tcp = new TcpService(service);
  Thread thread = new Thread(new ThreadStart(tcp.tcpService));
  thread.Start();
  }
  }
  public static void Main()
  {
  TcpServiceServer Service = new TcpServiceServer();
  }
  }
  public class TcpService
  {
  public Socket service;
  public int connection = 0;
  public string message;
  public byte[] buffer = new byte[1024];
  public TcpService(Socket service)
  {
  this.service = service;
  }
  public void tcpService()
  {
  if (service != null)