.net中對Socket通信進(jìn)行了封裝垛孔,使用起來也是很方便的鹿榜,只需要記住服務(wù)器和客戶端的基本操作流程,在寫代碼時注意一點(diǎn)就行了土匀,圖片來自黑馬教學(xué)視頻的截圖子房,作為參考,記錄在此恒削。
記錄一些簡單的code:
1.服務(wù)器端
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("監(jiān)聽成功池颈!");
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];
//實(shí)際接收到的字節(jié)數(shù)
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];
//實(shí)際接收到的字節(jié)數(shù)
int r = socketSend.Receive(buf);
if (r == 0) break;
if(buf[0] == 0)//發(fā)送的是文字信息
{
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是服務(wù)器端和客戶端的核心代碼钓丰,這些核心代碼在加上其他的一些輔助code就可以組成通信躯砰。
二.telnet 服務(wù)器安裝
控制面板->程序與功能->打開或關(guān)閉windows功能->勾選安裝(telnet 服務(wù)器,telnet客戶端)携丁。等待安裝: