Created
August 6, 2020 16:37
-
-
Save wattanar/2e34cef7ba43142670ced9521b226b0d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Data; | |
using System.Drawing; | |
using System.Linq; | |
using System.Net.NetworkInformation; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
namespace WindowsFormsApp1 | |
{ | |
public partial class Form1 : Form | |
{ | |
TcpClient tcpClient = new TcpClient(); | |
NetworkStream networkStream = default(NetworkStream); | |
string readData = null; | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void button1_Click(object sender, EventArgs e) | |
{ | |
connectTcp(); | |
} | |
private void connectTcp() | |
{ | |
Thread t = new Thread(getMessage); | |
try | |
{ | |
tcpClient = new TcpClient(); | |
tcpClient.Connect("127.0.0.1", 1234); | |
t.Start(); | |
} | |
catch (Exception ex) | |
{ | |
t.Abort(); | |
tcpClient.Close(); | |
MessageBox.Show(ex.Message); | |
} | |
} | |
private void getMessage() | |
{ | |
string returnData; | |
try | |
{ | |
while (true) | |
{ | |
networkStream = tcpClient.GetStream(); | |
var buffSize = tcpClient.ReceiveBufferSize; | |
byte[] inStream = new byte[buffSize]; | |
networkStream.Read(inStream, 0, buffSize); | |
returnData = Encoding.ASCII.GetString(inStream); | |
readData = returnData; | |
invokeMsg(); | |
} | |
} | |
catch (Exception) | |
{ | |
connectTcp(); | |
} | |
} | |
private void invokeMsg() | |
{ | |
if (this.InvokeRequired) | |
{ | |
this.Invoke(new MethodInvoker(invokeMsg)); | |
} | |
else | |
{ | |
textBox1.Text = readData; | |
} | |
} | |
private void button2_Click(object sender, EventArgs e) | |
{ | |
try | |
{ | |
byte[] outStream = Encoding.ASCII.GetBytes("Send data to server."); | |
networkStream = tcpClient.GetStream(); | |
networkStream.Write(outStream, 0, outStream.Length); | |
networkStream.Flush(); | |
} | |
catch (Exception) | |
{ | |
connectTcp(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment