I want to create a client socket to a web server knowing its hostname and port. I am asking this question from java background where you can simply write something like this
Socket MyClient;
try
{
MyClient = new Socket("Hostname", PortNumber);
}
catch (IOException e)
{
System.out.println(e);
}
Is there a similar way to write that in C# ?
No need to reinvent the wheel if you plan to use the socket for HTTP communication. You can use the WebClient class to do the dirty work for you.
here sample for you.
private string getHTTP(string url)
{
TcpClient clientSocket = new TcpClient();
NetworkStream networkStream = null;
long port = 7777;
try
{
try
{
clientSocket.Connect(url,port );
}
catch { MessageBox.Show("Server is not Working", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning); return "Server is not working"; }
byte[] sendbyte = Encoding.ASCII.GetBytes(url);
networkStream = clientSocket.GetStream();
networkStream.Write(sendbyte, 0, sendbyte.Length);
networkStream.Flush();
}
catch { MessageBox.Show("Streaming Error", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning); return "Error"; }
// receive Message from DNS Server
byte[] receivedata = new byte[clientSocket.ReceiveBufferSize];
networkStream.Read(receivedata, 0, clientSocket.ReceiveBufferSize);
string urlnew = Encoding.ASCII.GetString(receivedata);
return urlnew;
}
More you should reference this link
From the answers provided an idea jumped out of my mind , this is what i think could be the simple answer:
public Socket getSocket1(string Hostname, int PortNmber)
{
TcpClient client = new TcpClient(Hostname, PortNumber);
return client.Client;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.