|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Starting socket programming in c#
Hi all
I want to begin socket programming in c# and I am doing my first try. I know that I have to run my server program in coomand environment, but I can 't do that. I want someone to describe the steps exactly to me. here is my code, I have two files, tcpechoserver for server code and tcpechoclient for client code : --------------------------- tcpechoserver --------------------------- using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; namespace sock { class TcpEchoServer { private const int BUFSIZE = 32; static void main(string[] args) { args[0] = "TcpEchoServer"; args[1] = "hello"; args[2] = "8000"; if (args.Length < 1) { throw new ArgumentException("Parameters : <server> <word> [<port>]"); } string server = args[0]; byte[] byteBuffer = Encoding.ASCII.GetBytes(args[1]); int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7; TcpListener listener = null; try { listener = new TcpListener(IPAddress.Any, servPort); listener.Start(); } catch (SocketException se) { Console.WriteLine(se.ErrorCode + ":" + se.Message); Environment.Exit(se.ErrorCode); } byte[] rcvBuffer = new byte[BUFSIZE]; int byteRcvd; for (; ; ) { TcpClient client = null; NetworkStream netStream = null; try { client = listener.AcceptTcpClient(); netStream = client.GetStream(); Console.Write("Handling client-"); int totalBytesEchoed = 0; while ((byteRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) { netStream.Write(rcvBuffer, 0, byteRcvd); totalBytesEchoed += byteRcvd; } Console.WriteLine("echoed {0} bytes.", totalBytesEchoed); netStream.Close(); client.Close(); } catch (Exception e) { Console.WriteLine(e.Message); netStream.Close(); } } } } } ----------- tcpechoclient ------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; using System.IO; using System.Net.Sockets; using System.Net; namespace sock { class TcpEchoClient { static void Main(string[] args) { args[0] = "TcpEchoServer"; args[1] = "hello"; args[2] = "8000"; if ((args.Length < 2) || (args.Length > 3)) { throw new ArgumentException("Parameters : <Server> <Word> [<Port>]"); } string server = args[0]; byte[] byteBuffer = Encoding.ASCII.GetBytes(args[1]); int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7; TcpClient client = null; NetworkStream netStream = null; try { client = new TcpClient(server, servPort); Console.WriteLine("Connect to Server.... sending ....."); netStream = client.GetStream(); netStream.Write(byteBuffer, 0, byteBuffer.Length); Console.WriteLine("sent {0} bytes to server ....", byteBuffer.Length); int totalBytesRcvd = 0; int byteRcvd = 0; while (totalBytesRcvd < byteBuffer.Length) { if ((byteRcvd = netStream.Read(byteBuffer, totalBytesRcvd, byteBuffer.Length - totalBytesRcvd)) == 0) { Console.WriteLine("Connection Closed"); break; } totalBytesRcvd += byteRcvd; } Console.WriteLine("Recived {0} From Server : {1}", totalBytesRcvd, Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd)); } catch (ArgumentException) { // Show the user that 7 cannot be divided by 2. Console.WriteLine("7 is not divided by 2 integrally."); } catch (Exception e) { Console.WriteLine(e.Message); } finally { netStream.Close(); } } } } |
|
#2
|
|||
|
|||
|
First, locate the TcpEchoServer.exe, double-click it to get it to run. The code you have does not require any command-line arguments so you can just double-click on TcpEchoServer.exe to get it started. A blank command prompt window should show up, this is when you know the TcpEchoServer is running.
Next, is the client. I made the same mistake you made. Since you are running this on your machine locally, the line that says: args[0] = "TcpEchoServer"; should be changed to: args[0] = "localhost"; All you have to do now is locate TcpEchoClient.exe and double-click on it. Since you have already hard-coded those values, you don't need to supply any command-line parameters. Also, for your server, is there any use of those 3 hard-coded parameters you have? I think those you should only need for the client, and not for the server. Remember, the client is the one that is initiating the communication so it is the one that needs to provide this information. The server merely listens and waits for incoming data. Let me know if you have any further problems. |
|
#3
|
|||
|
|||
|
hello DrFace,thanks for your reply to me
i have mistake , i added this code because i want to reply without command line but i don't reply and i forgot to erase this section.excuse me. please help me. args[0] = "Localhost"; args[1] = "hello"; args[2] = "8000"; [IMG]<img src="debug.jpg" />[/IMG] |
|
#4
|
|||
|
|||
|
It should work, what happens when you try to run it?
Try the following code you should see the server echo it back. -------------- tcpechoserver -------------- Code:
using System;
using System.Net;
using System.Net.Sockets;
class TcpEchoServer
{
private const int BUFSIZE = 32; // Size of receive buffer
static void Main(string[] args)
{
int servPort = 7;
TcpListener listener = null;
try
{
// Create a TCPListener to accept client connections
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
}
catch (SocketException se)
{
Console.WriteLine(se.ErrorCode + ": " + se.Message);
Environment.Exit(se.ErrorCode);
}
byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
int bytesRcvd; // Received byte count
for(;;) // Run forever, accepting and servicing connections
{
TcpClient client = null;
NetworkStream netStream = null;
try
{
client = listener.AcceptTcpClient(); // Get client connection
netStream = client.GetStream();
Console.WriteLine("Handling client - ");
// Receive until client closes connection, indicated by 0 return value
int totalBytesEchoed = 0;
while((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
{
netStream.Write(rcvBuffer, 0, bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);
// Close the stream and socket. We are done with this client!
netStream.Close();
client.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
netStream.Close();
}
}
}
}
------------- tcpechoclient ------------- Code:
using System;
using System.Text;
using System.IO;
using System.Net.Sockets;
class TcpEchoClient
{
static void Main(string[] args)
{
String server = "localhost"; // Server name or IP address
// Convert input string to bytes
byte[] byteBuffer = Encoding.ASCII.GetBytes("This is a test...");
// Use port argument if supplied, otherwise default to 7
int servPort = 7;
TcpClient client = null;
NetworkStream netStream = null;
try
{
// Create socket that is connected to server on specified port
client = new TcpClient(server, servPort);
Console.WriteLine("Connected to server... sending echo strin");
netStream = client.GetStream();
// Send the encoded string to the server
netStream.Write(byteBuffer, 0, byteBuffer.Length);
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
int totalBytesRcvd = 0; // Total bytes received so far
int bytesRcvd = 0; // Bytes received in last read
// Receive the same string back from server
while (totalBytesRcvd < byteBuffer.Length)
{
if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd, byteBuffer.Length - totalBytesRcvd)) == 0)
{
Console.WriteLine("Connection closed prematurely.");
break;
}
totalBytesRcvd += bytesRcvd;
}
Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd, Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
netStream.Close();
client.Close();
}
}
}
|
|
#5
|
|||
|
|||
|
hello how are you?
1) in server's program : server accept any ipaddress using by (IPADDRESS.ANY) in client 's program: student.Connect( ????, 5006); i don't know ipaddress 's server because server and client don't exist in same network 2) Socket student= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if i want that work with tcp/ip ,what am i doing? thank you for guid bye. |
|
#6
|
|||
|
|||
|
hi how are you
please resolve error in this programs please server: ---------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; namespace socket { public partial class Form1 : Form { private Socket connection; private Thread readThread; private NetworkStream socketStream; private BinaryWriter writer; private BinaryReader reader; public Form1() { InitializeComponent(); readThread = new Thread(new ThreadStart(RunServer)); readThread.Start(); } public void RunServer() { TcpListener listener; int counter = 1; try { listener = new TcpListener(5555); listener.Start(); while (true) { connection = listener.AcceptSocket(); socketStream = new NetworkStream(connection); writer = new BinaryWriter(socketStream); reader = new BinaryReader(socketStream); tbxDisplay.Text += "Connection" + counter + "Received.\r\n"; writer.Write("Server: Connection Successfully"); string reply = ""; do { try { reply = reader.ReadString(); tbxDisplay.Text += "\r\n" + reply; } catch (Exception) { break; } } while (connection.Connected); tbxDisplay.Text += "\r\n User Terminate Connection"; writer.Close(); reader.Close(); socketStream.Close(); connection.Close(); ++counter; } } catch (Exception error) { MessageBox.Show(error.ToString()); } } private void btnSend_Click(object sender, EventArgs e) { try { if (connection != null) { writer.Write("Server : " + tbxSend.Text); tbxDisplay.Text += "server : " + tbxSend.Text; tbxSend.Clear(); } } catch (SocketException) { tbxDisplay.Text += "\nError writing object"; } } private void Form1_Closing(object sender, CancelEventArgs e) { System.Environment.Exit(System.Environment.ExitCod e); writer.Write("Server : Terminate"); connection.Close(); } private void btnSend_KeyDown(object sender, KeyEventArgs e) { try { if (connection != null) { writer.Write("Server : " + tbxSend.Text); tbxDisplay.Text += "server : " + tbxSend.Text; tbxSend.Clear(); } } catch (SocketException) { tbxDisplay.Text += "\nError writing object"; } catch (Exception) { MessageBox.Show("hale"); } } } } client: ------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; namespace socketClient { public partial class Form1 : Form { private Thread readThread; private NetworkStream output; private BinaryWriter writer; private BinaryReader reader; private string message = ""; public Form1() { InitializeComponent(); readThread = new Thread(new ThreadStart(RunClient)); readThread.Start(); } public void RunClient() { TcpClient client; try { client = new TcpClient(); client.Connect("127.0.0.1", 5555); output = client.GetStream(); writer = new BinaryWriter(output); // reader = new BinaryReader(output); do { try { // message = reader.ReadString(); // tbxDisplay.Text += "\r\n" + message; // MessageBox.Show("hale"); } catch (Exception) { System.Environment.Exit(System.Environment.ExitCod e); } } while (message!="Server:Terminate"); tbxDisplay.Text += "\r\nClosing Connection"; writer.Close(); reader.Close(); output.Close(); client.Close(); Application.Exit(); } catch (Exception error) { MessageBox.Show(error.ToString()); } } private void btnSend_Click(object sender, EventArgs e) { try { writer.Write("Client : " + tbxSend.Text); tbxDisplay.Text += "Client : " + tbxSend.Text+"\r\n"; tbxSend.Clear(); } catch (SocketException ioe) { tbxDisplay.Text += "\nError writing object"; } } private void Form1_Closing(object sender, CancelEventArgs e) { System.Environment.Exit(System.Environment.ExitCod e); } private void btnSend_KeyPress(object sender, KeyPressEventArgs e) { try { writer.Write("Client : " + tbxSend.Text); tbxDisplay.Text += "Client : " + tbxSend.Text+"\r\n"; tbxSend.Clear(); } catch (SocketException ioe) { tbxDisplay.Text += "\nError writing object"; } } } } |
![]() |
| Viewing: Dev Articles Community Forums > Programming > .NET Development > Starting socket programming in c# |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|