1.服务端
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private TcpListener _tcplistener; private Socket clientSocket; private Thread receiveThread; private void button1_Click(object sender, EventArgs e) { Thread startListenThread = new Thread(new ThreadStart(StartListening)); startListenThread.Start(); } private void StartListening() { int port = 11000; _tcplistener = new TcpListener(port); _tcplistener.Start(); while (true) { try { Socket s = _tcplistener.AcceptSocket(); clientSocket = s; receiveThread = new Thread(new ThreadStart(ReceiveClient)); receiveThread.Start(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } private void ReceiveClient() { try { Socket client = clientSocket; bool keepalive = true; while (keepalive) { Byte[] buffer = new Byte[1024]; client.Receive(buffer); string clientcommand = System.Text.Encoding.ASCII.GetString(buffer); ShowMsg(clientcommand); } client.Close(); keepalive = false; } catch (Exception ex) { } } delegate void ShowMsgDelegate(string str); private void ShowMsg(string msg) { ShowMsgDelegate ShowMsg = new ShowMsgDelegate(ShowMessage); this.Invoke(ShowMsg, new object[] { msg }); } private void ShowMessage(string msg) { richTextBox1.AppendText(msg); } } }
2.客户端
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace TcpClientTestNew { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSend_Click(object sender, EventArgs e) { string message = txtSendMsg.Text; byte[] outbytes = System.Text.Encoding.Default.GetBytes(message.ToCharArray()); ns.Write(outbytes, 0, outbytes.Length); } TcpClient tcpClient; private NetworkStream ns; private void StartConnect() { try { // tcpClient = new TcpClient(); // tcpClient.Connect(IPAddress.Parse(txtIP.Text), Int32.Parse(txtPort.Text)); // ns = tcpClient.GetStream(); // } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void Form1_Load(object sender, EventArgs e) { StartConnect(); } } }
原文:http://www.cnblogs.com/ike_li/p/5003332.html