C#中客户端和服务器之间的套接字编程
本文关键字:套接字 编程 之间 服务器 客户端 | 更新日期: 2023-09-27 18:29:37
这里我想问一下如何通过套接字编程在客户端(在Windows上,使用C#.NET)和服务器(在Ubuntu上,使用C)之间创建通信。如果服务器客户端都是C#或C,我已经成功地做到了,但不知道该怎么做。我试着在几个网站上查找信息,但找不到确切的信息。我感谢您的评论。非常感谢。
以下是客户端上的简单代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
// Receiving byte array
byte[] bytes = new byte[1024];
Socket senderSock;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_connect_Click(object sender, EventArgs e)
{
try
{
// Create one SocketPermission for socket access restrictions
SocketPermission permission = new SocketPermission(
NetworkAccess.Connect, // Connection permission
TransportType.Tcp, // Defines transport types
"", // Gets the IP addresses
SocketPermission.AllPorts // All ports
);
// Ensures the code to have permission to access a Socket
permission.Demand();
// Resolves a host name to an IPHostEntry instance
IPHostEntry ipHost = Dns.GetHostEntry("");
// Gets first IP address associated with a localhost
IPAddress ipAddr = ipHost.AddressList[0];
// Creates a network endpoint
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);
// Create one Socket object to setup Tcp connection
senderSock = new Socket(
ipAddr.AddressFamily,// Specifies the addressing scheme
SocketType.Stream, // The type of socket
ProtocolType.Tcp // Specifies the protocols
);
senderSock.NoDelay = false; // Using the Nagle algorithm
// Establishes a connection to a remote host
senderSock.Connect(ipEndPoint);
}
catch (Exception exc) { MessageBox.Show(exc.ToString()); }
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
// Sending message
//<Client Quit> is the sign for end of data
string theMessageToSend = text_IP.Text;
byte[] msg = Encoding.Unicode.GetBytes(theMessageToSend + "<Client Quit>");
// Sends data to a connected Socket.
int bytesSend = senderSock.Send(msg);
}
catch (Exception exc) { MessageBox.Show(exc.ToString()); }
}
}
}
这是服务器(C)中的代码
include "stdio.h"
#include "stdlib.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "netinet/in.h"
#include "error.h"
#include "strings.h"
#include "unistd.h"
#include "arpa/inet.h"
#define ERROR -1
#define MAX_CLIENTS
#define MAX_DATA 1024
main(int argc, char **argv)
{
struct sockaddr_in server;
struct sockaddr_in client;
int sock;
int new,i;
int sockaddr_len = sizeof(struct sockaddr_in);
printf("sockaddr_len");
int data_len;
char data[MAX_DATA];
char temp[MAX_DATA];
if((sock = socket(AF_INET, SOCK_STREAM, 0)) == ERROR)
{
perror("server socket: ");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[1]));
server.sin_addr.s_addr = INADDR_ANY;
bzero(&server.sin_zero, 8);
if((bind(sock, (struct sockaddr *)&server, sockaddr_len)) == ERROR)
{
perror("bind : ");
exit(-1);
}
if((listen(sock, MAX_CLIENTS)) == ERROR)
{
perror("listen");
exit(-1);
}
printf("'nThe TCPServer Waiting for client on port %d'n",ntohs(server.sin_port));
fflush(stdout);
while(1) // Better signal handling required
{
if((new = accept(sock, (struct sockaddr *)&client, &sockaddr_len)) == ERROR)
{
perror("accept");
exit(-1);
}
printf("New Client connected from port no %d and IP %s'n", ntohs(client.sin_port), inet_ntoa(client.sin_addr));
data_len = 1;
while(data_len)
{
data_len = recv(new, data, MAX_DATA, 0);
printf("'nRecieved mesg from client: %s", data);
for( i = 0; data[ i ]; i++)
{
/* if(data[i]=='a' || data[i]=='e' || data[i]=='i' ||data[i]=='o' || data[i]=='u' )
data[ i ] = toupper( data[ i ] );
else */
data[ i ] = data[ i ] ;
}
if(data_len)
{
send(new, data, data_len, 0);
data[data_len] = ''0';
printf("'nSent mesg to client: %s", data);
}
}
printf("Client disconnected'n");
close(new);
}
close(sock);
}
套接字是一个通用概念,不特定于任何语言。您可以继续使用相同的C Ubuntu服务器代码和C#Windows客户端代码。
你需要注意的几件事是:
- 如何绑定服务器&客户端和使用的协议
- 防火墙设置
希望你能从这些输入开始
快乐编码:)
所以我假设您的客户至少可以相互交谈。但您的问题似乎是从C#以Unicode格式发送文本,然后在客户端以ASCII格式接收。除非"C"客户端的默认值不是ASCII。
在客户端代码中,您使用空主机名调用GetHostEntry
。这将为您提供客户端的IP地址。
您应该使用服务器的主机名调用GetHostEntry
:
// Resolves a host name to an IPHostEntry instance
IPHostEntry ipHost = Dns.GetHostEntry("Server.Host.Name");
// Gets first IP address associated with a localhost
IPAddress ipAddr = ipHost.AddressList[0];
// Creates a network endpoint
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);