62,046
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
private IPEndPoint ep;
private Socket soc;
private Thread myThread;
private byte[] bytes;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
ep = new IPEndPoint(IPAddress.Parse("192.168.1.106"), 9050);
soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
soc.Bind(ep);
soc.Listen(50);
}
private void Recive()
{
try
{
//while (true)//这里while注释的原因是想手动发而不用无限循环
//{
try
{
//Socket mySocket = soc.Accept();
bytes = Encoding.Default.GetBytes(TextBox1.Text);
soc.Send(bytes);
Thread.Sleep(2000);
}
catch (Exception ex)
{
}
//}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
myThread = new Thread(new ThreadStart(Recive));
myThread.Name = "b";
myThread.Start();
}
}
public partial class Form1 : Form
{
private IPEndPoint enLoap;
private Socket mySocket;
private Thread myThread = null;
private EndPoint ep;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
enLoap = new IPEndPoint(IPAddress.Parse("192.168.1.106"), 9050); ;
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
mySocket.Connect(enLoap);
ep = (EndPoint)enLoap;
myThread = new Thread(new ThreadStart(Recive));
myThread.Name = "c";
myThread.Start();
}
private void Recive()
{
try
{
while (true)
{
try
{
if (mySocket == null)
{
Thread.Sleep(1000);
//continue;
}
else
{
if (listBox1.Items.Count > 10)
{
listBox1.Items.Clear();
}
byte[] b = new byte[1024];
int size = mySocket.Receive(b);
string strbuff = Encoding.Default.GetString(b, 0, size);
if (!String.IsNullOrEmpty(strbuff))
{
listBox1.Items.Add("收到消息: " + strbuff);
}
}
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (myThread != null & myThread.ThreadState != ThreadState.Unstarted && myThread.ThreadState != ThreadState.Stopped)
{
myThread.Abort();
}
if (mySocket != null)
{
mySocket.Close();
}
}
}
private void Recive()
{
try
{
Socket mySocket = soc.Accept();
bytes = Encoding.Default.GetBytes("现在时间: " + this.textBox1.Text);
mySocket.SendTo(bytes, ep);
}
catch (Exception ex)
{
}
finally
{
} }