Created
April 27, 2016 19:21
-
-
Save SamyCoenen/7778c29d1a9d64cccb7f6133ab2c2487 to your computer and use it in GitHub Desktop.
c# socket send read
This file contains 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
private StreamWriter swSender; | |
private StreamReader srReceiver; | |
private TcpClient tcpServer; | |
private Thread thrMessaging; | |
private IPAddress ipAddr; | |
private bool Connected; | |
private void InitializeConnection() | |
{ | |
// Parse the IP address | |
string ipAdress = "XXX.XXX.XXX.XXX"; | |
ipAddr = IPAddress.Parse(ipAdress); | |
// Start a new TCP connections to the chat server | |
tcpServer = new TcpClient(); | |
try | |
{ | |
tcpServer.Connect(ipAddr, 2002); | |
swSender = new StreamWriter(tcpServer.GetStream()); | |
// Start the thread for receiving messages and further communication | |
thrMessaging = new Thread(new ThreadStart(ReceiveMessages)); | |
thrMessaging.Start(); | |
Connected=true; | |
} | |
catch (Exception e2) | |
{ | |
MessageBox.Show(e2.ToString()); | |
} | |
} | |
private void ReceiveMessages() | |
{ | |
// Receive the response from the server | |
srReceiver = new StreamReader(tcpServer.GetStream()); | |
while (Connected) | |
{ | |
String con = srReceiver.ReadLine(); | |
string StringMessage = HttpUtility.UrlDecode(con, System.Text.Encoding.UTF8); | |
processMessage(StringMessage); | |
} | |
} | |
private void SendMessage(String p) | |
{ | |
if (p != "") | |
{ | |
p = HttpUtility.UrlEncode(p, System.Text.Encoding.UTF8); | |
swSender.WriteLine(p); | |
swSender.Flush(); | |
} | |
} | |
//bron: http://stackoverflow.com/questions/5999180/sockets-send-strings-from-java-to-c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment