Server端配置 参考代码

1)设置基本参数



/// <summary>
///以本机作测试
/// </summary>
private IPAddress serverIP = IPAddress.Parse("192.168.0.105");
/// <summary>
///完整终端地址
/// </summary>
private IPEndPoint serverFullAddr;
/// <summary>
/// 连接套接字
/// </summary>
private Socket sock;


2)启动服务器端


serverIP = IPAddress.Parse(tbxIP.Text);
try
{
//设置IP和端口
serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxPort.Text));
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//指定本地主机地址和端口号
sock.Connect(serverFullAddr);
btnConn.Enabled = false;
 MessageBox.Show("连接成功");
btnClose.Enabled = true;
sock.Close();

}
catch (Exception ee)
{
           MessageBox.Show("连接失败"+ee.ToString());
       }


3)停止服务端


sock.Close();//关闭Socket连接


Client端 参考代码

1)设置基本参数


/// <summary>
/// 以本机作测试,IP
/// </summary>
private IPAddress serverIP = IPAddress.Parse("127.0.0.1");


/// <summary>
/// 完整终端地址
/// </summary>
private IPEndPoint serverFullAddr;
/// <summary>
/// 连接套接字
/// </summary>
private Socket sock;
/// <summary>
/// 监听线程
/// </summary>
Thread myThead = null;


2)启动服务器  


myThead = new Thread(new ThreadStart(BeginListen));
myThead.Start();
btnStart.Enabled = false;
btnstop.Enabled = true;


3)设置侦听


/// <summary>
/// 设置监听
/// </summary>
private void BeginListen()
{
//IP
serverIP = IPAddress.Parse(tbxIP.Text);
//设置IP,端口
serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxPort.Text));
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

//指定本地主机地址和端口号
sock.Bind(serverFullAddr);
lbxMessage.Invoke(new SetTextCallback(SetText), "启动成功 时间:" + DateTime.Now, 1);
byte[] message = new byte[1024];
string mess = "";
while (true)
{
try
{
sock.Listen(5);//设置监听频率
Socket newSocket = sock.Accept();//阻塞方式
int bytes = newSocket.Receive(message);//接收数据
mess = Encoding.Default.GetString(message, 0, bytes);//对接收字节编码(S与C 两端编码格式必须一致不然中文乱码)(当接收的字节大于1024的时候 这应该是循环接收,测试就没有那样写了)
//do
//{
// bytes = newSocket.Receive(message, message.Length, 0);
// mess = mess + Encoding.ASCII.GetString(message, 0, bytes);
//}
//while (bytes > 0);

lbxMessage.Invoke(new SetTextCallback(SetText), mess, 1);//子线程操作主线程UI控件


//获取客户端的IP和端口
string ip11 = newSocket.RemoteEndPoint.AddressFamily.ToString();

mess = "已接收数据: "+ mess +" 来自:" +ip11+ " 当前时间为:" + DateTime.Now; //处理数据
newSocket.Send(Encoding.Default.GetBytes(mess));//向客户端发送数据

}
catch (SocketException se)
{
lbxMessage.Invoke(new SetTextCallback(SetText), mess + se, 1);

}
}
}


4)生命委托


delegate void SetTextCallback(string text, int num);
private void SetText(string text, int num)
{
lbxMessage.Items.Add(text);
}


5)停止服务


try
{
sock.Close();
//中止监听
myThead.Abort();
btnStart.Enabled = true;
btnstop.Enabled = false;
lbxMessage.Items.Add("停止成功 时间:" + DateTime.Now);
}
catch (Exception ee)
{
lbxMessage.Text = "停止失败。。" + ee;
}


5)接收消息


private void Sending(IAsyncResult rec_socket)
{
//发送给客户端的消息
string sendmsg = "";
Socket socket = (Socket)rec_socket.AsyncState;
try
{
if (socket.Connected)
{
byte[] msgBuff = Encoding.UTF8.GetBytes(sendmsg);
socket.Send(msgBuff);
}
else
{
Console.WriteLine("Error!", "Error!");
}
}
catch
{
Console.WriteLine("Error!", "Error!");
}
}