标签:read str mil sock star pad stream eve protoc
服务端代码
using System; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; namespace ServerForm { public partial class Server : Form { public Server() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } Socket serverClient = null; Thread thread = null; private static byte[] result = new byte[1024]; private void btnConnection_Click(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse(txtIpName.Text);//Ip serverClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化Socket参数分别为 serverClient.Bind(new IPEndPoint(ip, Convert.ToInt32(txtPort.Text))); serverClient.Listen(100); ShowMsg("开始监听!"); thread = new Thread(JtSocket); thread.IsBackground = true; thread.Start(); } Socket socket = null; void JtSocket() { while (true) { socket = serverClient.Accept(); socket.Receive(result); string reviceMsg = System.Text.Encoding.UTF8.GetString(result); ShowMsg("接收到数据"+reviceMsg); } } public void ShowMsg(string str) { string time = DateTime.Now.ToString(); string Ystr = ""; if (txtMsg.Text!="") { Ystr =txtMsg.Text + "\r\n"; } txtMsg.Text = Ystr +(time+"\r\n"+ str); } private void btnSend_Click(object sender, EventArgs e) { string senMsg = txtSendInfo.Text; if (senMsg!="") { byte[] msg = System.Text.Encoding.UTF8.GetBytes(senMsg); socket.Send(msg); ShowMsg("向客户端发送" + senMsg); } else { MessageBox.Show("没有可发送的数据", "提示"); } } } }
客户端:
using System; using System.Windows.Forms; using System.Net.Sockets; using System.Threading; using System.Net; namespace ClientForm { public partial class Client : Form { public Client() { InitializeComponent(); TextBox.CheckForIllegalCrossThreadCalls = false;//防止新线程调用主线程卡死 } Socket clientSocket = null; Thread thread = null; byte[] result = new byte[1024 * 1024 * 2]; private void btnConnection_Click(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse(txtIpName.Text);//Ip地址 clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); clientSocket.Connect(new IPEndPoint(ip,Convert.ToInt32(txtPort.Text)));//实例化IPEndPoing并且建立连接 thread = new Thread(ReviceMsg);//初始化线程 thread.IsBackground = true; thread.Start(); ShowMsg("连接成功!"); } public void ReviceMsg() { while (true) { clientSocket.Receive(result); string reviceMsg = System.Text.Encoding.UTF8.GetString(result); ShowMsg(reviceMsg); } } void ShowMsg(string str) { string time = DateTime.Now.ToString(); string Ystr = ""; if (txtMsg.Text!="") { Ystr = txtMsg.Text + "\r\n"; } txtMsg.Text = Ystr + (time+"\r\n"+str); } private void btnSendInfo_Click(object sender, EventArgs e) { string senMsg = txtInfo.Text; if (senMsg != "") { byte[] msg = System.Text.Encoding.UTF8.GetBytes(senMsg); clientSocket.Send(msg); ShowMsg("向服务端发送:" + senMsg); } else { MessageBox.Show("没有可发送的信息", "提示"); } } } }
标签:read str mil sock star pad stream eve protoc
原文地址:http://www.cnblogs.com/DaJia/p/7506376.html