[Tutor] Need help with sockets
James Duffy
devsfan1830 at gmail.com
Sat Apr 19 21:44:55 CEST 2008
For a part of a program, I need to send a text string to another machine in
a IM style app. I've done this in C# but never in python. The server is in
C# so I just need a client side program that can listen for and display
incoming messages as well as send messages. Ive managed to make a socket and
connect but I don't know how to setup a listen thread and a sender function.
Can someone help? Below is C# code for the listener/send function of my
client that id made. I basically hafta turn this into python. This method
runs inside a thread.
void RunClient()
{
TcpClient myClient; // instantiate TcpClient for sending data to server
try
{
Output to screen: Attempting connection\r\n"
// Step 1: Create TcpClient
myClient = new TcpClient();
// Step 2: Connect to server
myClient.Connect(address.Text,int.Parse(port.Text));
// Step 3: Create a Network Stream associated with TcpClient
myNetStream = myClient.GetStream();
// Step 4: Create objects for writing and reading across stream
myWriter = new BinaryWriter(myNetStream);
myReader = new BinaryReader(myNetStream);
// loop until server signals termination
do
{
// Step 5: Processing phase
try
{
// read message from server
message = myReader.ReadString();
inbound.Text +="\r\n" + message;
}
// handle exception if error in reading server data
catch (Exception)
{
System.Environment.Exit( System.Environment.ExitCode);
}
}
while (message != "SERVER>>> TERMINATE");
status.Text += "\r\nClosing connection.\r\n";
// Step 6: Close connection
myWriter.Close();
myReader.Close();
myNetStream.Close();
myClient.Close();
Application.Exit();
}
// handle exception if error in establishing connection
Catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080419/b43ce12f/attachment.htm
More information about the Tutor
mailing list