public Form1()
{
InitializeComponent();
}
int icount;
Thread thread;//接收数据的线程
delegate void SetReceivedToLabelCallBack(string msg, bool isSeconds);//数据接收线程到窗体的跨线程调用委托
Socket clientSock;
private void button1_Click(object sender, EventArgs e)
{
aa();
}
private void aa()
{
try
{
int port = 9999;
string host = "192.168.100.176";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
clientSock.Connect(ipe);//连接到服务器
DisplayReceivedMsg("Conneting...", false);
thread = new Thread(new ThreadStart(receiveThread));
thread.Start();
}
catch (ArgumentNullException e)
{
DisplayReceivedMsg("ArgumentNullException: "+ e.Message,false);
}
catch (SocketException e)
{
DisplayReceivedMsg("SocketException: "+ e.Message,false);
}
}
private void receiveThread()
{
try
{
while (true)
{
byte[] buffer = new byte[1024];
int receivedBytesCount = clientSock.Receive(buffer);
string receivedStr = System.Text.Encoding.ASCII.GetString(buffer);
icount += 1;
DisplayReceivedMsg(receivedStr + "/r/n", true);
}
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
}
public void DisplayReceivedMsg(string msg, bool isSeconds)
{
if (richTextBox1.InvokeRequired)//如果是跨线程调用
{
SetReceivedToLabelCallBack d = new SetReceivedToLabelCallBack(DisplayReceivedMsg);
this.Invoke(d, new object[] { msg, isSeconds });
}
else
{
richTextBox1.AppendText("接收到:" + icount.ToString() + "次数!" + msg );
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (thread != null)
{
thread.Abort();
thread = null;
}
if (clientSock != null)
{
clientSock.Close();
clientSock = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
string sendStr = "hello!This is a socket test";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
Console.WriteLine("Send Message");
clientSock.Send(bs, bs.Length, 0);//发送测试信息
}
}
}
-----------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace Keygoe
{
public class SocketService
{
delegate void SetReceivedToLabelCallBack(string msg, bool isSeconds);//数据接收线程到窗体的跨线程调用委托
private string MyIP; //string host = "127.0.0.1";
private int MyPort;
private Socket MySocket;
IPAddress MyIPAddress;
IPEndPoint MyIPEndPoint;
Thread myThread;
TextBox myTextBox;
Socket newSocket;
public SocketService(TextBox TB)
{
this.MyIP = "192.168.100.176";
this.MyPort = 9999;
this.myTextBox = TB;
}
public SocketService(string sIP, int sPort, TextBox TB)
{
this.MyIP = sIP;
this.MyPort = sPort;
this.myTextBox = TB;
}
public bool Initial()
{
try
{
MyIPAddress = IPAddress.Parse(MyIP);
MyIPEndPoint = new IPEndPoint(MyIPAddress, MyPort);
MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //);//创建一个Socket类
MySocket.Bind(MyIPEndPoint); //绑定MyIPEndPoint端口
MySocket.Listen(0);//开始监听
return true;
}
catch
{
return (false);
}
}
private void BeginListen()
{
while (true)
{
try
{
newSocket = MySocket.Accept();
//接收包的代码还没写
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = newSocket.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
DisplayReceivedMsg(recvStr,true);
}
catch
{
}
}
}
//开始监听
public void Start()
{
try
{
this.myThread = new Thread(new ThreadStart(BeginListen));
myThread.Start();
}
catch
{
}
}
public void Stop()
{
try
{
this.myThread.Abort();//中止线程
this.MySocket.Close();//释放资源
}
catch { }
}
public void sendmsg(string sendStr)
{
//string sendStr = "123456789";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
newSocket.Send(bs, bs.Length, 0);//返回客户端成功信息
}
public void DisplayReceivedMsg(string msg, bool isSeconds)
{
if (myTextBox.InvokeRequired)//如果是跨线程调用
{
SetReceivedToLabelCallBack d = new SetReceivedToLabelCallBack(DisplayReceivedMsg);
myTextBox.Invoke(d, new object[] { msg, isSeconds });
}
else
{
myTextBox.AppendText(msg);
}
}
}
}