Socket通信基本流程图
.net中对Socket通信进行了封装,使用起来也是很方便的,只需要记住服务器和客户端的基本操作流程,在写代码时注意一点就行了,图片来自黑马教学视频的截图,作为参考,记录在此。
记录一些简单的code:
1.服务器端
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
IPAddress ip;
if (IPAddress.TryParse(txtIp.Text, out ip))
{
try
{
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
socketWatch.Bind(point);
ShowMsg("监听成功!");
socketWatch.Listen(10);
Thread th = new Thread(Listen);
th.IsBackground = true;
th.Start(socketWatch);
}
catch { }
}
void Listen(object o)
{
Socket socketWatch = o as Socket;
while(true)
{
try
{
Socket socket = socketWatch.Accept();
_dicSocket.Add(socket.RemoteEndPoint.ToString(),socket);
cbSocket.Items.Add(socket.RemoteEndPoint.ToString());
cbSocket.SelectedIndex = 0;
ShowMsg(socket.RemoteEndPoint.ToString() + ":" + "连接成功");
Thread th = new Thread(DataReceive);
th.IsBackground = true;
th.Start(socket);
}
catch { }
}
}
void DataReceive(object o)
{
socketSend = o as Socket;
while (true)
{
try
{
byte[] buf = new byte[1024 * 1024 * 5];
//实际接收到的字节数
int r = socketSend.Receive(buf);
if (r == 0) break;
string str = Encoding.UTF8.GetString(buf, 0, r);
ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str);
}
catch
{
}
}
}
2.客户端
try
{
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip;
if (IPAddress.TryParse(txtIP.Text, out ip))
{
IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text));
socketSend.Connect(point);
ShowMsg("连接成功!");
Thread th = new Thread(DataReceive);
th.IsBackground = true;
th.Start();
}
}
catch { }
void DataReceive()
{
while (true)
{
try
{
byte[] buf = new byte[1024 * 1024 * 5];
//实际接收到的字节数
int r = socketSend.Receive(buf);
if (r == 0) break;
if(buf[0] == 0)//发送的是文字信息
{
string str = Encoding.UTF8.GetString(buf, 1, r - 1);
ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str);
}
else if(buf[0] == 1)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = @"C:\Users\cgy\Desktop";
sfd.Filter = "所有文件|*.*";
sfd.ShowDialog(this);
string path = sfd.FileName;
using (FileStream fsWrite = new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write))
{
fsWrite.Write(buf, 1, r - 1);
}
MessageBox.Show("保存成功!");
}
else if(buf[0] == 2)
{
Shake();
}
}
catch
{
}
}
}
上述Code是服务器端和客户端的核心代码,这些核心代码在加上其他的一些辅助code就可以组成通信。
二.telnet 服务器安装
控制面板->程序与功能->打开或关闭windows功能->勾选安装(telnet 服务器,telnet客户端)。等待安装: