using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace TPCL.MySocket
{
class CSocket
{
private Socket socket = null;
public int Open(string host, int port)
{
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
try
{
if (socket != null)
socket.Close();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ipe);
if (socket.Connected)
{
return 1;
}
else
return -1;
}
catch (Exception)
{
return -1;
//throw;
}
}
public void Send(string Data)
{
try
{
if (this.socket != null)
{
string sendStr = Data.Trim();
byte[] bs = System.Text.Encoding.Default.GetBytes(sendStr);
//发送信息
socket.Send(bs);
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Close()
{
if(this.socket != null)
this.socket.Close();
}
public string Read()
{
byte[] buffer = new byte[1024];
int receiveLength = socket.Receive(buffer);
string Data = Encoding.ASCII.GetString(buffer, 0, receiveLength);
Console.WriteLine("接收服务器消息:{0}", Data);
return Data;
/*
byte[] buffer = new byte[1024];
int receiveLength = 0;
int index = 0;
while (true)
{
receiveLength = socket.Receive(buffer, 1024, SocketFlags.None);
//index += receiveLength;
if (receiveLength == 0)
break;
}
string Data = Encoding.ASCII.GetString(buffer, 0, receiveLength);
return Data;
*/
}
}
}