// Get host related information. hostEntry = Dns.Resolve(server); // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception that occurs when the host IP Address is not compatible with the address family // (typical in the IPv6 case). foreach(IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, port); Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if(tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return s; } // This method requests the home page content for the specified server. private static string SocketSendReceive(string server, int port) { string request = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; Byte[] bytesSent = Encoding.ASCII.GetBytes(request); Byte[] bytesReceived = new Byte[256];
// Create a socket connection with the specified server and port. Socket s = ConnectSocket(server, port); if (s == null) return ("Connection failed");
// Send request to the server. s.Send(bytesSent, bytesSent.Length, 0);
// Receive the server home page content. int bytes = 0; string page = "Default HTML page on " + server + ":\r\n"; // The following will block until te page is transmitted. do { bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes); } while (bytes > 0);
return page; }
public static void Main(string[] args) { string host; int port = 80; if (args.Length == 0) // If no server name is passed as argument to this program, // use the current host name as the default. host = Dns.GetHostName(); else host = args[0]; string result = SocketSendReceive(host, port); Console.WriteLine(result); } } 详细请参考:http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpref/html/frlrfsystemnetsocketssocketclasstopic.asp
1. 先生成一个Socket类
2. 调用该类的Socket方法
3. 调用Send方法
4. 再调用Receive方法就可以了这是同步的步骤,如果使用异步就要麻烦一些
bind
listen
accept connect
receive send
send receive大概就是这样
接受: try
{ while (true)
{ Byte[] ByteRecv = new Byte[256];
this.mySocket.Receive(ByteRecv);
string strRecv = Encoding.BigEndianUnicode.GetString(ByteRecv);
if (this.rtbReceive.InvokeRequired)
{ this.rtbReceive.Invoke(new EventHandler(ChangeRtb), new object[] { strRecv, EventArgs.Empty }); }
else
{
this.rtbReceive.AppendText(strRecv + "\r\n");
}
}
}
catch (Exception ex)
{ MessageBox.Show("Receive Message Error" + ex.Message);
发送:
private void btnSend_Click(object sender, EventArgs e)
{
try
{
// Server = new IPEndPoint(((IPEndPoint)sockets[0].RemoteEndPoint).Address, ((IPEndPoint)sockets[2].RemoteEndPoint).Port);
string strSend = "Server--->" + rtbSend.Text + "\r\n";
Byte[] ByteSend = Encoding.BigEndianUnicode.GetBytes(strSend);
mySocket.Send(ByteSend);
}
catch { MessageBox.Show("连接尚未建立,无法发送."); }
}
我就是搞不懂
不在同一 局域网.怎么通信的.
例如: 家里局域网的一台机器 和 公司里局域网的一台机器.怎么用socket 通信.
需要看哪些资料?
如果当前使用的是无连接协议(如 UDP),则根本不需要侦听连接。调用 ReceiveFrom 方法可接受任何传入的数据报。使用 SendTo 方法可将数据报发送到远程主机。
若要在执行过程中使用单独的线程处理通信,请使用下面的方法,这些方法适用于异步操作模式。 如果当前使用的是面向连接的协议(如 TCP),则可使用 Socket、BeginConnect 和 EndConnect 方法来连接侦听主机。通过使用 BeginSend 和 EndSend 方法,或者使用 BeginReceive 和 EndReceive 方法,可以进行异步数据通信。可以使用 BeginAccept 和 EndAccept 处理传入的连接请求。
如果当前使用的是无连接协议(如 UDP),则可以使用 BeginSendTo 和 EndSendTo 来发送数据报,而使用 BeginReceiveFrom 和 EndReceiveFrom 来接收数据报。
如果对一个套接字执行多个异步操作,它们不一定按启动时的顺序完成。当数据发送和数据接收完成之后,可使用 Shutdown 方法来禁用 Socket。在调用 Shutdown 之后,可调用 Close 方法来释放与 Socket 关联的所有资源。Socket 类允许使用 SetSocketOption 方法来配置 Socket。可使用 GetSocketOption 方法来检索这些设置。注意 如果编写较简单的应用程序,而且只需同步数据传输,则可以考虑使用 TcpClient、TcpListener 和 UdpClient。这些类为 Socket 通信提供了更简单、对用户更友好的接口。[C#]
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;public class GetSocket
{
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.Resolve(server); // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if(tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
} // This method requests the home page content for the specified server.
private static string SocketSendReceive(string server, int port)
{
string request = "GET / HTTP/1.1\r\nHost: " + server +
"\r\nConnection: Close\r\n\r\n";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[256];
// Create a socket connection with the specified server and port.
Socket s = ConnectSocket(server, port); if (s == null)
return ("Connection failed");
// Send request to the server.
s.Send(bytesSent, bytesSent.Length, 0);
// Receive the server home page content.
int bytes = 0;
string page = "Default HTML page on " + server + ":\r\n"; // The following will block until te page is transmitted.
do {
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);
return page;
}
public static void Main(string[] args)
{
string host;
int port = 80; if (args.Length == 0)
// If no server name is passed as argument to this program,
// use the current host name as the default.
host = Dns.GetHostName();
else
host = args[0]; string result = SocketSendReceive(host, port);
Console.WriteLine(result);
}
}
详细请参考:http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpref/html/frlrfsystemnetsocketssocketclasstopic.asp