90 lines
1.3 KiB
C
Executable File
90 lines
1.3 KiB
C
Executable File
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <pthread.h>
|
|
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
|
|
#include "tcp.h"
|
|
|
|
#define LINE_SIZE 256
|
|
|
|
typedef void *(*thread_t)(void*);
|
|
typedef void *thread_param_t;
|
|
|
|
void *receive_thread(socket_fd_t socket)
|
|
{
|
|
while (1){
|
|
int chr;
|
|
|
|
int s = recv(socket, &chr, 1, 0);
|
|
|
|
if (s < 0) {
|
|
perror("receive_thread (recv):");
|
|
close(socket);
|
|
exit(1);
|
|
}
|
|
else if (s == 0) {
|
|
exit(1);
|
|
}
|
|
else {
|
|
putchar(chr);
|
|
fflush(stdout);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
int main(int argc, char *argv[])
|
|
{
|
|
pthread_t recv_thread;
|
|
socket_fd_t socket;
|
|
char *tmp;
|
|
int port;
|
|
char line[LINE_SIZE];
|
|
|
|
if (argc < 2) {
|
|
printf("tcp: not enough input arguments\n");
|
|
return 1;
|
|
}
|
|
|
|
if ((tmp = strchr(argv[1], ':'))) {
|
|
port = atoi(tmp+1);
|
|
*tmp = '\0';
|
|
|
|
printf("Assuming client mode: Host:%s, Port:%d\n", argv[1], port);
|
|
|
|
socket = tcp_connect(argv[1], port);
|
|
}
|
|
else {
|
|
port = atoi(argv[1]);
|
|
|
|
printf("Assuming server mode: Port:%d\n", port);
|
|
|
|
socket = tcp_accept(port);
|
|
}
|
|
|
|
if (socket < 0) {
|
|
return socket;
|
|
}
|
|
|
|
/*START*/
|
|
|
|
pthread_create(&recv_thread, NULL, (thread_t)&receive_thread,
|
|
(thread_param_t)socket);
|
|
|
|
while (1) {
|
|
fgets(line, sizeof(line), stdin);
|
|
|
|
if (write(socket, line, strlen(line)) != strlen(line)) {
|
|
perror("main (write):");
|
|
close(socket);
|
|
exit(1);
|
|
}
|
|
}
|
|
|
|
}
|