我正在制作一个可以在Visual FoxPro中访问的C#套接字库。理想情况下,库将包含两个函数:ReceiveMessage和SendMessage。在每次调用时,该函数应该{open connection - >读/写 - >关闭连接}。我在http://www.csharp-examples.net/socket-send-receive/找到了我要找的大部分内容;但是,现在我必须在编译dll之前测试(在同一台机器上)修改后的代码。
我一直在积极拒绝接触"错误。虽然我已经包含了下面的所有代码,所以你可以看到它在做什么,问题几乎肯定在底部的main()中。我有限的理解是我不能有两个连接到同一个端口,但我对如何修复它感到茫然。有没有人知道套接字可以给我一些指导如何测试这些函数(我是套接字的新手)?
namespace Sockets
{
class Sockets
{
private static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int received = 0; // how many bytes is already received
do
{
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Timeout.");
try
{
received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.IOPending ||
ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
// socket buffer is probably empty, wait and try again
Thread.Sleep(30);
}
else
throw ex; // any serious error occurr
}
} while (received < size);
}
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
private static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int sent = 0; // how many bytes is already sent
do
{
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Timeout.");
try
{
sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.IOPending ||
ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
// socket buffer is probably full, wait and try again
Thread.Sleep(30);
}
else
throw ex; // any serious error occurr
}
} while (sent < size);
}
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
public static string SendMessage(string ipAddress, string port, string message)
{
Socket socket = new TcpClient().Client;
try
{
socket.Connect(ipAddress, Int32.Parse(port));
Send(socket, Encoding.UTF8.GetBytes(message), 0, message.Length, 10000);
socket.Close();
return "Success";
}
catch (Exception e)
{
socket.Close();
return e.Message;
}
}
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
public static string ReceiveMessage(string ipAddress, string port, int bufferSize = 1024)
{
Socket socket = new TcpClient().Client;
try
{
socket.Connect(ipAddress, Int32.Parse(port));
byte[] buffer = new byte[bufferSize];
Receive(socket, buffer, 0, buffer.Length, 10000);
socket.Close();
return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
}
catch (Exception e)
{
socket.Close();
return e.Message;
}
}
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
}
}
class Program
{
static void Main(string[] args)
{
new Thread(delegate() {var test = Sockets.Sockets.SendMessage("localhost", "60010", "abcdefg");}).Start();
new Thread(delegate() {Console.WriteLine(Sockets.Sockets.ReceiveMessage("localhost", "60010"));}).Start();
var waitForEnter = Console.ReadLine();
}
}
答案 0 :(得分:0)
使用tilda作为尾随字符,这里是功能接收函数(旧代码已注释):
public static string ReceiveMessage(string ipAddress, string port, int bufferSize = 1024)
{
try
{
TcpListener serverSocket = new TcpListener(new System.Net.IPAddress(IPAddress.Parse(ipAddress).GetAddressBytes()), Int32.Parse(port));
serverSocket.Start();
TcpClient clientSocket = serverSocket.AcceptTcpClient();
NetworkStream networkStream = clientSocket.GetStream();
int bytesRead;
string buffer = "";
byte[] bytesFrom = new byte[bufferSize];
while (true)
{
bytesRead = networkStream.Read(bytesFrom, 0, bytesFrom.Length);
string incoming = System.Text.Encoding.ASCII.GetString(bytesFrom, 0, bytesRead);
buffer = buffer + incoming;
while (buffer.Contains("~"))
{
string msg = buffer.Substring(0, buffer.IndexOf("~"));
// buffer = buffer.Remove(0, msg.Length + 3);
return msg;
}
}
//var socket = new TcpListener(new IPAddress(IPAddress.Parse(ipAddress).GetAddressBytes()), Int32.Parse(port));
//try
//{
//byte[] buffer = new byte[bufferSize];
// Receive(socket, buffer, 0, buffer.Length, 10000);
// socket.Close();
// return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
//}
//catch (Exception e)
//{
// socket.Close();
// return e.Message;
//}
}
catch (Exception e)
{
return e.Message;
}
}