int port = 8080
string host = "192.168.1.206"
IPAddress ip = IPAddress.Parse(host)
IPEndPoint ipe = new IPEndPoint(ip, port)//把ip和端口转化为IPEndPoint实例
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)//创建一个Socket
Response.Write("Conneting...\n")
c.Connect(ipe)//连接到服务器
string sendStr = " hello!This is a socket test "
byte[] bs = Encoding.ASCII.GetBytes(sendStr)
c.Send(bs, bs.Length, 0)//发送测试信息
string recvStr = "Send Message "
byte[] recvBytes = new byte[1024]
int bytes
bytes = c.Receive(recvBytes, recvBytes.Length, 0)//从服务器端接受返回信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes)
Response.Write("Client Get Message:" + recvStr )//显示服务器返回信息
c.Close()
server
string portNo = ConfigurationManager.AppSettings["PortNo"]
IPAddress ServerIp = GetServerIP()
IPEndPoint iep = new IPEndPoint(ServerIp, int.Parse(portNo))
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
byte[] byteMessage = new byte[100]
try
{
socket.Bind(iep)
}
catch (Exception ex)
{
throw ex
}
while (flag)
{
try
{
socket.Listen(1)
Socket newSocket = socket.Accept()
newSocket.Receive(byteMessage)
string sTime = DateTime.Now.ToShortTimeString()
string msg = sTime + ":" + "Message from:"
msg += newSocket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage)
byte[] bs = Encoding.ASCII.GetBytes(msg)
newSocket.Send(bs)
}
catch (SocketException ex)
{
throw ex
}
}
Asp.net中C#使用Socket发送和接收TCP数据的方法。
具体程序代码如下:
using Systemusing System.Collections.Generic
using System.Net
using System.Net.Sockets
using System.Text
namespace ConsoleApplication1
{
public static class SocketTest
{
private static Encoding encode = Encoding.Default
/// <summary>
/// 监听请求
/// </summary>
/// <param name="port"></param>
public static void Listen(int port)
{
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
listenSocket.Bind(new IPEndPoint(IPAddress.Any, port))
listenSocket.Listen(100)
Console.WriteLine("Listen " + port + " ...")
while (true)
{
Socket acceptSocket = listenSocket.Accept()
string receiveData = Receive(acceptSocket, 5000) //5 seconds timeout.
Console.WriteLine("Receive:" + receiveData)
acceptSocket.Send(encode.GetBytes("ok"))
DestroySocket(acceptSocket) //import
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string Send(string host, int port, string data)
{
string result = string.Empty
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
clientSocket.Connect(host, port)
clientSocket.Send(encode.GetBytes(data))
Console.WriteLine("Send:" + data)
result = Receive(clientSocket, 5000 * 2) //5*2 seconds timeout.
Console.WriteLine("Receive:" + result)
DestroySocket(clientSocket)
return result
}
/// <summary>
/// 接收数据
/// </summary>
/// <param name="socket"></param>
/// <param name="timeout"></param>
/// <returns></returns>
private static string Receive(Socket socket, int timeout)
{
string result = string.Empty
socket.ReceiveTimeout = timeout
List<byte> data = new List<byte>()
byte[] buffer = new byte[1024]
int length = 0
try
{
while ((length = socket.Receive(buffer)) > 0)
{
for (int j = 0 j < length j++)
{
data.Add(buffer[j])
}
if (length < buffer.Length)
{
break
}
}
}
catch { }
if (data.Count > 0)
{
result = encode.GetString(data.ToArray(), 0, data.Count)
}
return result
}
/// <summary>
/// 销毁Socket对象
/// </summary>
/// <param name="socket"></param>
private static void DestroySocket(Socket socket)
{
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both)
}
socket.Close()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)