- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
[仅剩下两个小问题]
我试图用C编写一个简单的服务器/客户端,通过套接字发送消息。
它必须在Linux和Windows下运行。我发现了很多Linux的例子,但是很多例子都不支持Windows。
如果你能帮助我,那就太好了。
对于服务器,我有些不明白的地方。
我在服务器端做什么?
需要在Windows上初始化WSA,在Linux上不需要。
在服务器端为服务器创建套接字。
为服务器创建struct sockaddr\u in。
在任意IP上绑定套接字。
听一下插座。
接受连接,处理与newSocket的连接。
关闭新插座,重复6)。
只有当我不关闭newSocket时它才能正常工作,但是为什么呢?(EBADF错误)
Edit2之后的代码更新:
// IMPORTANT: On linker errors try -lws2_32 as Linkerparameter
#ifdef __WIN32__
# include <winsock2.h> // used for sockets with windows, needs startup / shutdown
# include <ws2tcpip.h> // for MinGW / socklen_t
# define INIT_SOCKET_SYSTEM WSADATA wsaData;if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {printf ("Error initialising WSA.\n");exit(6);}
# define CLEAR_SOCKET_SYSTEM WSACleanup();
# include <windows.h> // for Sleep
# define SLEEP Sleep(10); // sleeping 10ms
# define CLOSE_SOCKET_FUNCTION closesocket
#else
# include <sys/socket.h>
# define INIT_SOCKET_SYSTEM printf("Linux dont need a special init for sockets, so all fine.\n");
# define CLEAR_SOCKET_SYSTEM printf("Linux dont need a special clear for sockets, so all fine.\n");
# include <time.h>
# define SLEEP sleep(1); // sleeping a second :-/
# define CLOSE_SOCKET_FUNCTION close
#endif
#include <stdio.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <strings.h> // used for bzero
//used in the tutorial but not necessary!?
//#include <sys/types.h>
//#include <unistd.h>
//#include <stdlib.h>
/* could be still useful
// polling 10ms...
//#include <time.h>
//#define SLEEP time_t tStart, tEnd;time(&tStart);do {time(&tEnd);} while (difftime(tEnd, tStart) < 0.01);
*/
/* Random Sources
* http://pubs.opengroup.org/onlinepubs/9699919799/
* http://linux.die.net/man/2
* http://stackoverflow.com/questions/31765278/simple-webserver-wont-work
* http://blog.stephencleary.com/2009/05/using-socket-as-server-listening-socket.html
*
* http://cs.baylor.edu/~donahoo/practical/CSockets/WindowsSockets.pdf
*/
// functions
void createListenSocket(int * retListenSocket, const int port, bool * isRunning);
void listenFor(int * listenSocket, bool * isRunning);
void acceptFor(int * listenSocket, socklen_t * addrlen, bool * isRunning);
void handleConnection(int * inSocket, struct sockaddr_in * addClient);
// http://www.gnu.org/software/libc/manual/html_node/Cleanups-on-Exit.html
int * cleanSocket;
void cleanUp() {
CLOSE_SOCKET_FUNCTION(* cleanSocket);
CLEAR_SOCKET_SYSTEM
}
//[todo] WSAGetLastError handling for windows
int main(int argc, char ** argv) {
atexit(cleanUp);
bool isRunning = true;
socklen_t addressLen = sizeof(struct sockaddr_in);
// create listening socket
const int port = 15000;
int listenSocket;
cleanSocket = &listenSocket;
createListenSocket(&listenSocket, port, &isRunning);
listenFor(&listenSocket, &isRunning);
while (isRunning) {
acceptFor(&listenSocket, &addressLen, &isRunning);
SLEEP
}
return 0;
}
void createListenSocket(int * retListenSocket, const int port, bool * isRunning) {
INIT_SOCKET_SYSTEM
struct sockaddr_in addServer;
(* retListenSocket) = socket(AF_INET, SOCK_STREAM, 0);
int tErr = errno;
if ((* retListenSocket) > 0) {
printf("The socket was created (%i)\n", * retListenSocket);
} else {
printf("Couldnt create socket\n- ");
switch (tErr) {
case EACCES:
printf("Permission to create a socket of the specified type and/or protocol is denied.\n");
break;
case EAFNOSUPPORT:
printf("The implementation does not support the specified addServer family.\n");
break;
case EINVAL:
printf("Unknown protocol, or protocol family not available. OR Invalid flags in type.\n");
break;
case EMFILE:
printf("Process file table overflow.\n");
break;
case ENFILE:
printf("The system limit on the total number of open files has been reached.\n");
break;
case ENOBUFS:
printf("Insufficient memory is available. The socket cannot be created until sufficient resources are freed.\n");
break;
case ENOMEM:
printf("Insufficient memory is available. The socket cannot be created until sufficient resources are freed.\n");
break;
case EPROTONOSUPPORT:
printf("The protocol type or the specified protocol is not supported within this domain.\n");
break;
default:
printf("unspecified error %i ... \n", tErr);
break;
}
* isRunning = false;
return;
}
addServer.sin_family = AF_INET;
addServer.sin_addr.s_addr = INADDR_ANY;
addServer.sin_port = htons(port);
if (bind(* retListenSocket, (struct sockaddr * ) &addServer, sizeof(struct sockaddr_in)) == 0) {
printf("Socket bind successfull\n");
} else {
printf("Socket bind failed\n");
* isRunning = false;
return;
}
}
// http://linux.die.net/man/2/listen / http://pubs.opengroup.org/onlinepubs/9699919799/
void listenFor(int * listenSocket, bool * isRunning) {
int t = listen(* listenSocket, 10);
int tErr = errno;
if (t < 0) {
printf("Error while listening\n- ");
//perror("server: listen");
switch (tErr) {
case EADDRINUSE:
printf("Another socket is already listening on the same port.\n");
break;
case EBADF:
printf("The argument sockfd is not a valid descriptor.\n");
break;
case ENOTSOCK:
printf("The argument sockfd is not a socket\n");
break;
case EOPNOTSUPP:
printf("The socket is not of a type that supports the listen() operation\n");
break;
default:
printf("Undefined Error%i\n", tErr);
break;
}
* isRunning = false;
}
}
// http://linux.die.net/man/2/accept / http://pubs.opengroup.org/onlinepubs/9699919799/
void acceptFor(int * listenSocket, socklen_t * addrlen, bool * isRunning) {
struct sockaddr_in addClient;
memset(&addClient, 0, sizeof(addClient));
int NewSocket = accept(* listenSocket, (struct sockaddr *) &addClient, addrlen);
int tErr = errno;
//write(NewSocket, "Hoi\n", 4);
if (tErr != 0) {
printf("Error while accepting\n- ");
switch (tErr) {
case EAGAIN:
printf("The socket is marked nonblocking and no connections are present to be accepted. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities.\n");
break;
case EWOULDBLOCK:
printf("The socket is marked nonblocking and no connections are present to be accepted. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities.\n");
break;
case EBADF:
printf("The descriptor is invalid\n");
break;
case ECONNABORTED:
printf("A connection has been aborted.\n");
break;
case EFAULT:
printf("The addr argument is not in a writable part of the user addServer space.\n");
break;
case EINTR:
printf("The system call was interrupted by a signal that was caught before a valid connection arrived; see signal(7).\n");
break;
case EINVAL:
printf("Socket is not listening for connections, or addrlen is invalid (e.g., is negative). or (accept4()) invalid value in flags\n");
break;
case EMFILE:
printf("The per-process limit of open file descriptors has been reached.\n");
break;
case ENFILE:
printf("The system limit on the total number of open files has been reached.\n");
break;
case ENOBUFS:
printf("Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory.\n");
break;
case ENOMEM:
printf("Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory.\n");
break;
case ENOTSOCK:
printf("The descriptor references a file, not a socket.\n");
break;
case EOPNOTSUPP:
printf("The referenced socket is not of type SOCK_STREAM.\n");
break;
case EPROTO:
printf("Protocol error\n");
break;
default:
printf("Undefined Error %i\n", tErr);
break;
}
* isRunning = false;
} else if (NewSocket != -1) {
handleConnection(&NewSocket, &addClient);
}
}
void handleConnection(int * inSocket, struct sockaddr_in * addClient) {
if (* inSocket > 0){
int bufferSize = 1024;
char * buffer = malloc(bufferSize);
memset(buffer, '\0', bufferSize);
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n\r\n"
"<html><head><title>test</title>"
"<html><body><H1>Hello world</H1></body></html>";
printf("The Client is connected from %s ...\n", inet_ntoa((* addClient).sin_addr));
//[todo] handle full buffer
int received = recv(* inSocket, buffer, bufferSize, 0);
printf("%s\nbuffer size: %i\n", buffer, bufferSize);
send(* inSocket, response, strlen(response), 0);
printf("=> response send\n");
CLOSE_SOCKET_FUNCTION(* inSocket);
}
}
#ifdef __WIN32__
# include <winsock2.h> // used for sockets with windows, needs startup / shutdown
# include <ws2tcpip.h> // for MinGW / socklen_t / InetPtonA
# define INIT_SOCKET_SYSTEM WSADATA wsaData;if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {printf ("Error initialising WSA.\n");exit(6);}
# define CLEAR_SOCKET_SYSTEM WSACleanup();
# include <windows.h> // for Sleep
# define SLEEP Sleep(10); // sleeping 10ms
#else
# include <sys/socket.h>
# define INIT_SOCKET_SYSTEM printf("Linux dont need a special init for sockets, so all fine.\n");
# define CLEAR_SOCKET_SYSTEM printf("Linux dont need a special clear for sockets, so all fine.\n");
# include <time.h>
# define SLEEP sleep(1); // sleeping a second :-/
#endif
#include <stdio.h>
#include <sys/stat.h>
#include <stdbool.h>
// Step 1, create lokal Access point
void createSocket(int * mySocket);
// Step 2, create the target address
struct sockaddr_in getTargetAddress(char * ip, int port);
int * cleanSocket;
void cleanUp() {
close(* cleanSocket);
CLEAR_SOCKET_SYSTEM
}
int main() {
int mySocket;
// Step 1 create you Socket
createSocket(&mySocket);
// Step 2 get target
struct sockaddr_in serverAddress = getTargetAddress("127.0.0.1", 15000);
//struct sockaddr_in myAddress = getTargetAddress("127.0.0.1", 15000);
// Step 3 bind & connect or sendto
//bind(mySocket, (const struct sockaddr *) &myAddress, sizeof(myAddress));
//connect(mySocket, (const struct sockaddr * )&serverAddress, sizeof(serverAddress));
char * question = "Whats up?\n";
printf("sending %s\n", question);
//send(mySocket, question, strlen(question), 0); // try to use protocol?
sendto(mySocket, question, strlen(question), 0, (const struct sockaddr *) &serverAddress, sizeof(serverAddress));
printf("sended!\n");
close(mySocket);
return 0;
}
void createSocket(int * mySocket) {
INIT_SOCKET_SYSTEM
if ((* mySocket = socket(AF_INET, SOCK_STREAM, 0)) > 0) {
printf("Socket creation successful\n");
} else {
printf("Socket creation failed\n");
}
}
struct sockaddr_in getTargetAddress(char * ip, int port) {
struct sockaddr_in ret;
ret.sin_family = AF_INET;
ret.sin_addr.s_addr = inet_addr(ip);
ret.sin_port = htons(15000);
return ret;
}
int received
不在使用中。
mySocket = socket(AF_INET, SOCK_STREAM, 0)
struct sockaddr_in serverAddress = getTargetAddress("127.0.0.1", 15000);
struct sockaddr_in myAddress = getTargetAddress("Pseudo", 15000);
bind(mySocket, (const struct sockaddr *) &myAddress, sizeof(myAddress));
connect(mySocket, (const struct sockaddr * )&serverAddress, sizeof(serverAddress));
send(mySocket, question, strlen(question), 0);
mySocket = socket(AF_INET, SOCK_STREAM, 0)
struct sockaddr_in serverAddress = getTargetAddress("127.0.0.1", 15000);
connect(mySocket, (const struct sockaddr * )&serverAddress, sizeof(serverAddress));
send(mySocket, question, strlen(question), 0);
mySocket = socket(AF_INET, SOCK_STREAM, 0)
struct sockaddr_in serverAddress = getTargetAddress("127.0.0.1", 15000);
connect(mySocket, (const struct sockaddr * )&serverAddress, sizeof(serverAddress));
sendto(mySocket, question, strlen(question), 0, (const struct sockaddr *) &serverAddress, sizeof(serverAddress));
mySocket = socket(AF_INET, SOCK_STREAM, 0)
struct sockaddr_in serverAddress = getTargetAddress("127.0.0.1", 15000);
struct sockaddr_in myAddress = getTargetAddress("Pseudo", 15000);
bind(mySocket, (const struct sockaddr *) &myAddress, sizeof(myAddress));
sendto(mySocket, question, strlen(question), 0, (const struct sockaddr *) &serverAddress, sizeof(serverAddress));
最佳答案
它不会起作用,因为您从未调用connect()。您应该检查connect()、send()等调用的返回值。
解决方案:应该在创建套接字后调用connect。
connect(mySocket, (SOCKADDR *)&serverAddress, sizeof(sockaddr_in));
send(mySocket, question, strlen(question), 0);
关于c - 带有套接字的C服务器/客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38416571/
#include using namespace std; class C{ private: int value; public: C(){ value = 0;
这个问题已经有答案了: What is the difference between char a[] = ?string?; and char *p = ?string?;? (8 个回答) 已关闭
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 7 年前。 此帖子已于 8 个月
除了调试之外,是否有任何针对 c、c++ 或 c# 的测试工具,其工作原理类似于将独立函数复制粘贴到某个文本框,然后在其他文本框中输入参数? 最佳答案 也许您会考虑单元测试。我推荐你谷歌测试和谷歌模拟
我想在第二台显示器中移动一个窗口 (HWND)。问题是我尝试了很多方法,例如将分辨率加倍或输入负值,但它永远无法将窗口放在我的第二台显示器上。 关于如何在 C/C++/c# 中执行此操作的任何线索 最
我正在寻找 C/C++/C## 中不同类型 DES 的现有实现。我的运行平台是Windows XP/Vista/7。 我正在尝试编写一个 C# 程序,它将使用 DES 算法进行加密和解密。我需要一些实
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
有没有办法强制将另一个 窗口置于顶部? 不是应用程序的窗口,而是另一个已经在系统上运行的窗口。 (Windows, C/C++/C#) 最佳答案 SetWindowPos(that_window_ha
假设您可以在 C/C++ 或 Csharp 之间做出选择,并且您打算在 Windows 和 Linux 服务器上运行同一服务器的多个实例,那么构建套接字服务器应用程序的最明智选择是什么? 最佳答案 如
你们能告诉我它们之间的区别吗? 顺便问一下,有什么叫C++库或C库的吗? 最佳答案 C++ 标准库 和 C 标准库 是 C++ 和 C 标准定义的库,提供给 C++ 和 C 程序使用。那是那些词的共同
下面的测试代码,我将输出信息放在注释中。我使用的是 gcc 4.8.5 和 Centos 7.2。 #include #include class C { public:
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我的客户将使用名为 annoucement 的结构/类与客户通信。我想我会用 C++ 编写服务器。会有很多不同的类继承annoucement。我的问题是通过网络将这些类发送给客户端 我想也许我应该使用
我在 C# 中有以下函数: public Matrix ConcatDescriptors(IList> descriptors) { int cols = descriptors[0].Co
我有一个项目要编写一个函数来对某些数据执行某些操作。我可以用 C/C++ 编写代码,但我不想与雇主共享该函数的代码。相反,我只想让他有权在他自己的代码中调用该函数。是否可以?我想到了这两种方法 - 在
我使用的是编写糟糕的第 3 方 (C/C++) Api。我从托管代码(C++/CLI)中使用它。有时会出现“访问冲突错误”。这使整个应用程序崩溃。我知道我无法处理这些错误[如果指针访问非法内存位置等,
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 7 年前。
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,因为
我有一些 C 代码,将使用 P/Invoke 从 C# 调用。我正在尝试为这个 C 函数定义一个 C# 等效项。 SomeData* DoSomething(); struct SomeData {
这个问题已经有答案了: Why are these constructs using pre and post-increment undefined behavior? (14 个回答) 已关闭 6
我是一名优秀的程序员,十分优秀!