Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make chat server can choose port where it running #42

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions smallchat-server.c
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
* =========================================================================== */

#define MAX_CLIENTS 1000 // This is actually the higher file descriptor.
#define SERVER_PORT 7711
#define DEFAULT_SERVER_PORT 7711

/* This structure represents a connected client. There is very little
* info about it: the socket descriptor and the nick name, if set, otherwise
Expand Down Expand Up @@ -113,7 +113,7 @@ void freeClient(struct client *c) {
}

/* Allocate and init the global stuff. */
void initChat(void) {
void initChat(int server_port) {
Chat = chatMalloc(sizeof(*Chat));
memset(Chat,0,sizeof(*Chat));
/* No clients at startup, of course. */
Expand All @@ -122,11 +122,12 @@ void initChat(void) {

/* Create our listening socket, bound to the given port. This
* is where our clients will connect. */
Chat->serversock = createTCPServer(SERVER_PORT);
Chat->serversock = createTCPServer(server_port);
if (Chat->serversock == -1) {
perror("Creating listening socket");
exit(1);
}
printf("smallchat server is run on port %d \n", server_port);
}

/* Send the specified string to all connected clients but the one
Expand All @@ -148,8 +149,9 @@ void sendMsgToAllClientsBut(int excluded, char *s, size_t len) {
* 1. Accept new clients connections if any.
* 2. Check if any client sent us some new message.
* 3. Send the message to all the other clients. */
int main(void) {
initChat();
int main(int argc, char **argv) {
int server_port = argc == 2 ? atoi(argv[1]) : DEFAULT_SERVER_PORT;
initChat(server_port);

while(1) {
fd_set readfds;
Expand Down