TCP/IP 客户端套接字程序。这里我的主要要求是客户端发送消息,服务器接收消息并存储在 C#.Net 的数据库表中,使用服务器 IP 地址和端口号。
您正在谈论一个简单的服务器-客户端程序。
你需要做什么。
- 首先创建一个服务器程序并运行
- 创建客户端并使用连接到正在运行的服务器连接(“服务器IP”,端口)
- 现在,当客户端连接到服务器时,接收消息到服务器并使用数据库连接将该消息存储在数据库中
Guides :
-
写入服务器-http://csharp.net-informations.com/communications/csharp-server-socket.htm
-
写客户端-http://csharp.net-informations.com/communications/csharp-client-socket.htm
-
C# 数据库访问 [SQL] -http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm
更新 - 根据要求和指导,这里是一个工作客户端和一个服务器
CLIENT-
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace socket_prog
{
class Client
{
private static void Main(String[] args)
{
byte[] data = new byte[10];
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAdress = iphostInfo.AddressList[0];
IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 32000);
Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
client.Connect(ipEndpoint);
Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());
byte[] sendmsg = Encoding.ASCII.GetBytes("This is from Client\n");
int n = client.Send(sendmsg);
int m = client.Receive(data);
Console.WriteLine("" + Encoding.ASCII.GetString(data));
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("Transmission end.");
Console.ReadKey();
}
}
}
SERVER-
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace socket_prog
{
class Server
{
static void Main(string[] args)
{
byte[] buffer = new byte[1000];
byte[] msg = Encoding.ASCII.GetBytes("From server\n");
string data = null;
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = iphostInfo.AddressList[0];
IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 32000);
ConsoleKeyInfo key;
int count = 0;
Socket sock = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
sock.Bind(localEndpoint);
sock.Listen(5);
while (true)
{
Console.WriteLine("\nWaiting for clients..{0}", count);
Socket confd = sock.Accept();
int b = confd.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, b);
Console.WriteLine("" + data);
data = null;
confd.Send(msg);
Console.WriteLine("\n<< Continue 'y' , Exit 'e'>>");
key = Console.ReadKey();
if (key.KeyChar == 'e')
{
Console.WriteLine("\nExiting..Handled {0} clients", count);
confd.Close();
System.Threading.Thread.Sleep(5000);
break;
}
confd.Close();
count++;
}
}
}
}
首先运行服务器。然后运行客户端。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)