📄 form1.cs
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace SocketsSample
{
public partial class Form1 : Form
{
//listen on custom tcp port
private const int port = 38080;
public Form1()
{
InitializeComponent();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ListenerThread));
t.IsBackground = true;
t.Name = "SocketListener";
t.Start();
}
private void ListenerThread()
{
//create a new listener to listen on our custom port
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
listener.Start();
//Socket listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//listenerSocket.Bind(new IPEndPoint(IPAddress.Any, port));
//listenerSocket.Listen();
try
{
while (true)
{
//get incoming connection (blocking)
TcpClient incomingClient = listener.AcceptTcpClient();
//Socket incomingSocket = listenerSocket.Accept();
//get address of remove device
IPAddress senderAddress = ((IPEndPoint)incomingClient.Client.RemoteEndPoint).Address;
//IPAddress senderAddress = ((IPEndPoint)incomingSocket.RemoteEndPoint).Address;
//get a stream to read from the socket
NetworkStream ns = incomingClient.GetStream();
//NetworkStream ns = new NetworkStream(incomingSocket, true);
try
{
StreamReader sr = new StreamReader(ns, System.Text.Encoding.Unicode);
StreamWriter sw = new StreamWriter(ns, System.Text.Encoding.Unicode);
string operation = sr.ReadLine();
//this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { operation });
if (operation == "PROSPECT")
{
//sending the data as a plain string
string rawProspect = sr.ReadLine();
string[] fields = rawProspect.Split(',');
//perform simple validation of received data and send a response
if (fields.Length == 3)
{
//send acknowledgement
sw.WriteLine("OK");
}
else
{
sw.WriteLine("ERROR");
}
Prospect receivedProspect = new Prospect();
receivedProspect.Name = fields[0];
receivedProspect.Company = fields[1];
receivedProspect.Number = fields[2];
this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { senderAddress.ToString() + " " + receivedProspect.ToString() });
}
else if (operation == "FILE")
{
string filename = sr.ReadLine();
byte[] len = new byte[8];
ns.Read(len, 0, 8);
Int64 fileSize = BitConverter.ToInt64(len, 0);
FileStream fs = new FileStream(Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Personal), filename), FileMode.CreateNew);
byte[] buffer = new byte[256];
int bytesread = ns.Read(buffer, 0, buffer.Length);
int totalbytesread = bytesread;
try
{
while (totalbytesread < fileSize)
{
fs.Write(buffer, 0, bytesread);
bytesread = ns.Read(buffer, 0, buffer.Length);
totalbytesread += bytesread;
}
fs.Close();
sw.WriteLine("OK");
this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { senderAddress.ToString() + " " + filename });
}
catch
{
sw.WriteLine("ERROR");
}
}
}
catch
{
//transfer failed
this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { senderAddress.ToString() + " Failed"});
}
finally
{
//close the stream and associated socket
ns.Close();
}
}
}
finally
{
//stop the listener
listener.Stop();
//listenerSocket.Close();
}
}
private void AppendToListBox(string newItem)
{
listBox1.Items.Add(newItem);
}
private delegate void AppendToListBoxDelegate(string newItem);
private void btnShare_Click(object sender, EventArgs e)
{
IPAddress target;
try
{
target = IPAddress.Parse(txtRecipient.Text);
}
catch
{
MessageBox.Show("Invalid IP address");
return;
}
//create prospect object
Prospect p = new Prospect();
p.Name = txtName.Text;
p.Company = txtCompany.Text;
p.Number = txtNumber.Text;
//create new outbound socket
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(target, port));
NetworkStream ns = new NetworkStream(clientSocket, true);
StreamWriter sw = new StreamWriter(ns);
StreamReader sr = new StreamReader(ns);
try
{
//write a header to say that following data is a prospect record
sw.WriteLine("PROSPECT");
sw.WriteLine(p.ToString());
string response = sr.ReadLine();
switch (response)
{
case "OK":
this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { target.ToString() + " Sent successfully" });
break;
case "ERROR":
this.Invoke(new AppendToListBoxDelegate(AppendToListBox), new object[] { target.ToString() + " Failed to send" });
break;
}
}
catch(IOException ie)
{
MessageBox.Show("IO Exception trying to send: " + ie.ToString());
}
catch(SocketException se)
{
MessageBox.Show("Socket Exception trying to send: " + se.ToString());
}
finally
{
ns.Close();
}
}
private void btnFile_Click(object sender, EventArgs e)
{
//pick a file
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//only perform if file was selected
TcpClient tc = new TcpClient();
tc.Connect(new IPEndPoint(IPAddress.Parse(txtRecipient.Text), port));
try
{
//send a header to show it will be followed by a binary file
byte[] header = System.Text.Encoding.Unicode.GetBytes("FILE\r\n");
tc.Client.Send(header);
//send the filename
string filename = Path.GetFileName(openFileDialog1.FileName);
header = System.Text.Encoding.Unicode.GetBytes(filename + "\r\n");
tc.Client.Send(header);
//send the file length (int64 - 8 bytes)
FileInfo fi = new FileInfo(openFileDialog1.FileName);
byte[] buffer = BitConverter.GetBytes(fi.Length);
tc.Client.Send(buffer);
//send the file contents
SendFile(tc.Client, openFileDialog1.FileName);
}
catch (SocketException se)
{
MessageBox.Show(se.NativeErrorCode.ToString() + ": " + se.ToString());
}
finally
{
//close the connection
tc.Close();
}
}
}
//send file contents to a socket
private static void SendFile(Socket s, string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open);
byte[] buffer = new byte[256];
int bytesRead = fs.Read(buffer, 0, buffer.Length);
while (bytesRead > 0)
{
s.Send(buffer, bytesRead, SocketFlags.None);
//read next block
bytesRead = fs.Read(buffer, 0, buffer.Length);
}
fs.Close();
}
private void btnIP_Click(object sender, EventArgs e)
{
//get ip address for host name
IPHostEntry ihe = System.Net.Dns.GetHostEntry(txtHost.Text);
if (ihe.AddressList.Length > 0)
{
txtRecipient.Text = ihe.AddressList[0].ToString();
}
else
{
txtRecipient.Text = "";
}
}
}
[Serializable()]
public class Prospect
{
private string name;
private string company;
private string number;
public string Name
{
get { return name; }
set { name = value; }
}
public string Company
{
get { return company; }
set { company = value; }
}
public string Number
{
get { return number; }
set { number = value; }
}
public override string ToString()
{
return name + "," + company + "," + number;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -