参考: private void sendSocket( string sendData )
{
using ( Socket socket = new Socket( AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp ) )
{
IPHostEntry iPHostEntry = Dns.GetHostByName( ServerIp );
IPAddress[] iPAddressArr = iPHostEntry.AddressList;
IPAddress iPAddress = iPAddressArr[0];
IPEndPoint iPEndPoint = new IPEndPoint( iPAddress, Port );
try
{
socket.Connect( iPEndPoint );
}
catch
{
ResponseContent = "连接异常!";
throw;
}
byte[] sendDataBytes = new byte[ sendData.Length ];
sendDataBytes = Encoding.GetEncoding("GB2312").GetBytes( sendData );
socket.Send( sendDataBytes, sendDataBytes.Length, 0 );
byte[] recvBytes = new byte[1024];
int recvBytesLength = socket.Receive( recvBytes, recvBytes.Length, 0 );
ResponseContent = Encoding.GetEncoding("GB2312").GetString( recvBytes, 0, recvBytesLength );
socket.Shutdown( SocketShutdown.Both );
}
}
{
using ( Socket socket = new Socket( AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp ) )
{
IPHostEntry iPHostEntry = Dns.GetHostByName( ServerIp );
IPAddress[] iPAddressArr = iPHostEntry.AddressList;
IPAddress iPAddress = iPAddressArr[0];
IPEndPoint iPEndPoint = new IPEndPoint( iPAddress, Port );
try
{
socket.Connect( iPEndPoint );
}
catch
{
ResponseContent = "连接异常!";
throw;
}
byte[] sendDataBytes = new byte[ sendData.Length ];
sendDataBytes = Encoding.GetEncoding("GB2312").GetBytes( sendData );
socket.Send( sendDataBytes, sendDataBytes.Length, 0 );
byte[] recvBytes = new byte[1024];
int recvBytesLength = socket.Receive( recvBytes, recvBytes.Length, 0 );
ResponseContent = Encoding.GetEncoding("GB2312").GetString( recvBytes, 0, recvBytesLength );
socket.Shutdown( SocketShutdown.Both );
}
}
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,0);
IPAddress ip=IPAddress.Parse("172.31.1.21");
IPEndPoint sender = new IPEndPoint(ip,8089); EndPoint Remote = (EndPoint)(sender); newsock.SendTo(netdata,netdata.Length,0,Remote);
newsock.Close();