Here is a set of TCP and UDP clients and servers for a uppercase echo service (like echo, but convert to uppercase along the way).  I hope they are helpful.  Note that unlike some of the echo examples, these routines don't assume every line ends with a newline character (this was a problem with some of the Windows clients).

The various programs have been tested, and any TCP client will work with any TCP server (same for UDP), regardless of language or O.S. This did influence the structure especially of the Perl and Java examples, since the Windows clients didn't include newlines, resulting in a deadlock if the server expects a complete string. So the servers were modified so that they accept text without a newline at the end.




The Linux C examples are basically stolen from Internetworking with TCP/IP, Volume III by Comer and Stevens

Linux C client support routines

/* errexit.c - errexit */

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

/*------------------------------------------------------------------------
 * errexit - print an error message and exit
 *------------------------------------------------------------------------
 */
/*VARARGS1*/
int
errexit(const char *format, ...)
{
	va_list	args;

	va_start(args, format);
	vfprintf(stderr, format, args);
	va_end(args);
	exit(1);
}

/* connectsock.c - connectsock */

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#ifndef	INADDR_NONE
#define	INADDR_NONE	0xffffffff
#endif	/* INADDR_NONE */

extern int	errno;

int	errexit(const char *format, ...);

/*------------------------------------------------------------------------
 * connectsock - allocate & connect a socket using TCP or UDP
 *------------------------------------------------------------------------
 */
int
connectsock(const char *host, const char *service, const char *transport )
/*
 * Arguments:
 *      host      - name of host to which connection is desired
 *      service   - service associated with the desired port
 *      transport - name of transport protocol to use ("tcp" or "udp")
 */
{
	struct hostent	*phe;	/* pointer to host information entry	*/
	struct servent	*pse;	/* pointer to service information entry	*/
	struct protoent *ppe;	/* pointer to protocol information entry*/
	struct sockaddr_in sin;	/* an Internet endpoint address		*/
	int	s, type;	/* socket descriptor and socket type	*/


	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;

    /* Map service name to port number */
	if ( pse = getservbyname(service, transport) )
		sin.sin_port = pse->s_port;
	else if ( (sin.sin_port = htons((unsigned short)atoi(service))) == 0 )
		errexit("can't get \"%s\" service entry\n", service);

    /* Map host name to IP address, allowing for dotted decimal */
	if ( phe = gethostbyname(host) )
		memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);
	else if ( (sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE )
		errexit("can't get \"%s\" host entry\n", host);

    /* Map transport protocol name to protocol number */
	if ( (ppe = getprotobyname(transport)) == 0)
		errexit("can't get \"%s\" protocol entry\n", transport);

    /* Use protocol to choose a socket type */
	if (strcmp(transport, "udp") == 0)
		type = SOCK_DGRAM;
	else
		type = SOCK_STREAM;

    /* Allocate a socket */
	s = socket(PF_INET, type, ppe->p_proto);
	if (s < 0)
		errexit("can't create socket: %s\n", strerror(errno));

    /* Connect the socket */
	if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
		errexit("can't connect to %s.%s: %s\n", host, service,
			strerror(errno));
	return s;
}

/* connectTCP.c - connectTCP */

int	connectsock(const char *host, const char *service,
		const char *transport);

/*------------------------------------------------------------------------
 * connectTCP - connect to a specified TCP service on a specified host
 *------------------------------------------------------------------------
 */
int
connectTCP(const char *host, const char *service )
/*
 * Arguments:
 *      host    - name of host to which connection is desired
 *      service - service associated with the desired port
 */
{
	return connectsock( host, service, "tcp");
}

Linux C TCP client

/* UcaseClient.c */

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

#include "errexit.c"
#include "connectsock.c"
#include "connectTCP.c"

#define	LINELEN		128

/*------------------------------------------------------------------------
 * main - TCP client for UCASE service
 *------------------------------------------------------------------------
 */
int
main(int argc, char *argv[])
{
	char	*host = "localhost";	/* host to use if none supplied	*/
	char	*service = "echo";	/* default service name		*/

	switch (argc) {
	case 1:
		host = "localhost";
		break;
	case 3:
		service = argv[2];
		/* FALL THROUGH */
	case 2:
		host = argv[1];
		break;
	default:
		fprintf(stderr, "usage: TCPecho [host [port]]\n");
		exit(1);
	}
	TCPecho(host, service);
	exit(0);
}

/*------------------------------------------------------------------------
 * TCPecho - send input to UCASE service on specified host and print reply
 *------------------------------------------------------------------------
 */
int
TCPecho(const char *host, const char *service)
{
	char	buf[LINELEN+1];		/* buffer for one line of text	*/
	int	s, n;			/* socket descriptor, read count*/
	int	outchars, inchars;	/* characters sent and received	*/

	s = connectTCP(host, service);

	while (fgets(buf, sizeof(buf), stdin)) {
		buf[LINELEN] = '\0';	/* insure line null-terminated	*/
		outchars = strlen(buf);
		(void) write(s, buf, outchars);

		/* read it back */
		for (inchars = 0; inchars <outchars; inchars+=n ) {
			n = read(s, &buf[inchars], outchars - inchars);
			if (n < 0)
				errexit("socket read failed: %s\n",
					strerror(errno));
		}
		fputs(buf, stdout);
	}
}

Linux C server support routines

/* passivesock.c - passivesock */

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>

#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>

extern int	errno;

int	errexit(const char *format, ...);

unsigned short	portbase = 0;		/* port base, for non-root servers	*/

/*------------------------------------------------------------------------
 * passivesock - allocate & bind a server socket using TCP or UDP
 *------------------------------------------------------------------------
 */
int
passivesock(const char *service, const char *transport, int qlen)
/*
 * Arguments:
 *      service   - service associated with the desired port
 *      transport - transport protocol to use ("tcp" or "udp")
 *      qlen      - maximum server request queue length
 */
{
	struct servent	*pse;	/* pointer to service information entry	*/
	struct protoent *ppe;	/* pointer to protocol information entry*/
	struct sockaddr_in sin;	/* an Internet endpoint address		*/
	int	s, type;	/* socket descriptor and socket type	*/

	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;

    /* Map service name to port number */
	if ( pse = getservbyname(service, transport) )
		sin.sin_port = htons(ntohs((unsigned short)pse->s_port)
			+ portbase);
	else if ( (sin.sin_port = htons((unsigned short)atoi(service))) == 0 )
		errexit("can't get \"%s\" service entry\n", service);

    /* Map protocol name to protocol number */
	if ( (ppe = getprotobyname(transport)) == 0)
		errexit("can't get \"%s\" protocol entry\n", transport);

    /* Use protocol to choose a socket type */
	if (strcmp(transport, "udp") == 0)
		type = SOCK_DGRAM;
	else
		type = SOCK_STREAM;

    /* Allocate a socket */
	s = socket(PF_INET, type, ppe->p_proto);
	if (s < 0)
		errexit("can't create socket: %s\n", strerror(errno));

    /* Bind the socket */
	if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
		errexit("can't bind to %s port: %s\n", service,
			strerror(errno));
	if (type == SOCK_STREAM && listen(s, qlen) < 0)
		errexit("can't listen on %s port: %s\n", service,
			strerror(errno));
	return s;
}

/* passiveTCP.c - passiveTCP */

int	passivesock(const char *service, const char *transport,
		int qlen);

/*------------------------------------------------------------------------
 * passiveTCP - create a passive socket for use in a TCP server
 *------------------------------------------------------------------------
 */
int
passiveTCP(const char *service, int qlen)
/*
 * Arguments:
 *      service - service associated with the desired port
 *      qlen    - maximum server request queue length
 */
{
	return passivesock(service, "tcp", qlen);
}

Linux C TCP server

/* TCPechod.c - main, TCPechod */

#include <sys/types.h>
#include <sys/signal.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/errno.h>
#include <netinet/in.h>

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define	QLEN		   5	/* maximum connection queue length	*/
#define	BUFSIZE		4096

#include "errexit.c"
#include "passivesock.c"
#include "passiveTCP.c"

void	reaper(int);

/*------------------------------------------------------------------------
 * main - Concurrent TCP server for UCASE service
 *------------------------------------------------------------------------
 */
int
main(int argc, char *argv[])
{
	char	*service = "echo";	/* service name or port number	*/
	struct	sockaddr_in fsin;	/* the address of a client	*/
	int	alen;			/* length of client's address	*/
	int	msock;			/* master server socket		*/
	int	ssock;			/* slave server socket		*/

	switch (argc) {
	case	1:
		break;
	case	2:
		service = argv[1];
		break;
	default:
		errexit("usage: TCPechod [port]\n");
	}

	msock = passiveTCP(service, QLEN);

	(void) signal(SIGCHLD, reaper);

	while (1) {
		alen = sizeof(fsin);
		ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
		if (ssock < 0) {
			if (errno == EINTR)
				continue;
			errexit("accept: %s\n", strerror(errno));
		}
		switch (fork()) {
		case 0:		/* child */
			(void) close(msock);
			exit(TCPechod(ssock));
		default:	/* parent */
			(void) close(ssock);
			break;
		case -1:
			errexit("fork: %s\n", strerror(errno));
		}
	}
}

/*------------------------------------------------------------------------
 * TCPechod - echo data in uppercase until end of file
 *------------------------------------------------------------------------
 */
int
TCPechod(int fd)
{
	char	buf[BUFSIZ];
	int	cc, i;

	while (cc = read(fd, buf, sizeof buf)) {
		if (cc < 0)
			errexit("echo read: %s\n", strerror(errno));

		// convert it to uppercase
		for( i=0; i<cc; i++ )
			buf[i] = toupper( buf[i] );

		// send it back
		if (write(fd, buf, cc) < 0)
			errexit("echo write: %s\n", strerror(errno));
	}
	return 0;
}

/*------------------------------------------------------------------------
 * reaper - clean up zombie children
 *------------------------------------------------------------------------
 */
/*ARGSUSED*/
void
reaper(int sig)
{
	int	status;

	/* for Linux we need to reset the signal */
	(void) signal(SIGCHLD, reaper);

	while (wait3(&status, WNOHANG, (struct rusage *)0) >= 0)
		/* empty */;
}

/* connectUDP.c - connectUDP */

int	connectsock(const char *host, const char *service,
		const char *transport);

/*------------------------------------------------------------------------
 * connectUDP - connect to a specified UDP service on a specified host
 *------------------------------------------------------------------------
 */
int
connectUDP(const char *host, const char *service )
/*
 * Arguments:
 *      host    - name of host to which connection is desired
 *      service - service associated with the desired port
 */
{
	return connectsock(host, service, "udp");
}

Linux C UDP client

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

/* connectsock.c - connectsock */

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <netdb.h>
#include <string.h>
#include <stdlib.h>

#ifndef	INADDR_NONE
#define	INADDR_NONE	0xffffffff
#endif	/* INADDR_NONE */

int errno;
#include "errexit.c"
#include "connectsock.c"
#include "connectUDP.c"

#define	LINELEN		128

/*------------------------------------------------------------------------
 * main - UDP client for UCASE service
 *------------------------------------------------------------------------
 */
int
main(int argc, char *argv[])
{
	char	*host = "localhost";
	char	*service = "echo";

	switch (argc) {
	case 1:
		host = "localhost";
		break;
	case 3:
		service = argv[2];
		/* FALL THROUGH */
	case 2:
		host = argv[1];
		break;
	default:
		fprintf(stderr, "usage: UDPecho [host [port]]\n");
		exit(1);
	}
	UDPecho(host, service);
	exit(0);
}

/*------------------------------------------------------------------------
 * UDPecho - send input to UCASE service on specified host and print reply
 *------------------------------------------------------------------------
 */
int
UDPecho(const char *host, const char *service)
{
	char	buf[LINELEN+1];		/* buffer for one line of text	*/
	int	s, nchars;		/* socket descriptor, read count*/
	struct  sockaddr sin;		/* port to send to */
	int	sin_len;		/* length of structure */

	s = connectUDP( host, service );

	while (fgets(buf, sizeof(buf), stdin)) {
		buf[LINELEN] = '\0';	/* insure null-terminated */
		nchars = strlen(buf);
		/* send the message */
		(void) send( s, (void * )buf, nchars, 0 );

		/* get the reply */
		nchars = recvfrom( s, (void * )buf, sizeof(buf),
				0, &sin, &sin_len );
		buf[nchars] = 0;
		fputs(buf, stdout);
	}
}

/* passiveUDP.c - passiveUDP */

int	passivesock(const char *service, const char *transport,
		int qlen);

/*------------------------------------------------------------------------
 * passiveUDP - create a passive socket for use in a UDP server
 *------------------------------------------------------------------------
 */
int
passiveUDP(const char *service)
/*
 * Arguments:
 *      service - service associated with the desired port
 */
{
	return passivesock(service, "udp", 0);
}

Linux C UDP server

/* UDPtimed.c - main */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <ctype.h>

extern int	errno;

#include "passivesock.c"
#include "passiveUDP.c"
#include "errexit.c"

#define	UNIXEPOCH	2208988800	/* UNIX epoch, in UCT secs	*/

/*------------------------------------------------------------------------
 * main - Iterative UDP server for UCASE service
 *------------------------------------------------------------------------
 */
int
main(int argc, char *argv[])
{
	struct sockaddr fsin;	/* the from address of a client	*/
	char	*service = "time";	/* service name or port number	*/
	char	buf[100];		/* "input" buffer; any size > 0	*/
	int	sock;			/* server socket		*/
	time_t	now;			/* current time			*/
	int	alen;			/* from-address length		*/
	int	buflen;			/* # of character received	*/
        int	i;

	switch (argc) {
	case	1:
		break;
	case	2:
		service = argv[1];
		break;
	default:
		errexit("usage: UDPtimed [port]\n");
	}

	sock = passiveUDP(service);

	while (1) {
		alen = sizeof(fsin);
		buflen = recvfrom(sock, buf, sizeof(buf), 0,
				(struct sockaddr *)&fsin, &alen);

		if ( buflen > 0 )
	        {
			/* convert it to uppercase */
			for( i=0; i<buflen; i++ )
				buf[i] = toupper(  buf[i] );
			(void) sendto(sock, buf, buflen, 0,
				(struct sockaddr *)&fsin, alen );
		}
	}
}

Perl TCP client

#!/usr/bin/perl -w
require v5.6.0;
use strict;
use IO::Socket::INET;

my ($remote,$port, $line);
$remote  = shift || 'localhost';
$port    = shift || 2345;  # random port

my $sock = IO::Socket::INET->new
(
   PeerAddr => $remote,
   PeerPort => $port,
   Proto => "tcp",
);

die unless $sock;

# send stuff to the server
while ( $line = <> )
{
# send the line to the server
	print $sock $line;
# wait for it to come back
	$line = <$sock>;
	print $line;
}

close $sock            || die "close: $!";

Perl TCP server

#!/usr/bin/perl -w
require v5.6.0;
use strict;
use IO::Socket::INET;

my ($port, $line );
$port    = shift || 2345;  # random port

my $sock = IO::Socket::INET->new
(
   LocalPort => $port,
   Listen=>5,
   Proto => "tcp",
);

die unless $sock;

# set up a subroutine to respond to child exit messages
sub REAPER { 
    my $waitedpid;
    $SIG{CHLD} = \&REAPER;  # loathe sysV
    $waitedpid = wait;
}
# set up the inital signal request
$SIG{CHLD} = \&REAPER;

while(1)
{
    my $newpid;
    my $line;

# get a connect request
    my $client = $sock->accept( );
# sometimes getting a bad socket here, so do a sanity check
    next unless $client;

# split off a child
    $newpid = fork();
    if ( $newpid == 0)
    {
    	# I'm the child - wait for data to arrive
	# continue as long as we can get more data
DLOOP:	while( 1==1 )
	{
		my $res = recv $client, $line, 128, 0;

		# if no data, bail out
		if ( !defined($res) || length($line)==0 )
		{
			last DLOOP;
		}

		# have data, send it back
		#	print $client uc($line);
		send $client, uc($line), 0;
	}
	# finished!

##	close $client            || die "close CLIENT: $!";
	exit;
    }
    else
    {
    	# parent - get another request
	close $client;
    }
}

Perl UDP client

#!/usr/bin/perl -w
#require v5.6.0;
use strict;
use IO::Socket::INET;

my ($remote,$port, $line);
$remote  = shift || 'localhost';
$port    = shift || 2345;  # random port

my $sock = IO::Socket::INET->new
(
   PeerAddr => $remote,
   PeerPort => $port,
   Proto => "udp",
);

die unless $sock;

# send stuff to the server
while ( $line = <> )
{
# send the line to the server
	print $sock $line;
# wait for it to come back
	$line = <$sock>;
	print $line;
}

close $sock            || die "close: $!";

Perl UDP server

#!/usr/bin/perl -w
#require v5.6.0;
use strict;
use IO::Socket::INET;

my ($port, $line );
$port    = shift || 2345;  # random port

my $sock = IO::Socket::INET->new
(
   LocalPort => $port,
   Proto => "udp",
);

die unless $sock;

while(1)
{
    my $line;
    my $remote_socket;

# get a message
    $remote_socket = recv( $sock, $line, 128, 0 );

# send it back in uppercase
    send( $sock, uc($line), 0, $remote_socket );
}

Java examples - These were compiled and tested under Linux, but the Java bytecode executables were later tested (but not recompiled) under Windows XP

Java TCP client

import java.io.*;
import java.net.*;

public class ucase_j_tc {
    public static void main(String[] args) throws IOException {

        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            echoSocket = new Socket(args[0], Integer.parseInt(args[1]));
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: "+args[0]+".");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: " +
	    		args[0] + ".");
            System.exit(1);
        }

	BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
	String userInput;

	while ((userInput = stdIn.readLine()) != null) {
	    out.println(userInput);
	    System.out.println("echo: " + in.readLine());
	}

	out.close();
	in.close();
	stdIn.close();
	echoSocket.close();
    }
}

Java TCP server

import java.net.*;
import java.io.*;

class UcaseServerThread extends Thread {
    private Socket socket = null;

    public UcaseServerThread(Socket socket) {
        super("EchoServerThread");
	this.socket = socket;
    }

    public void run() {
	int dcount;	// # of characters read
        byte [] data = new byte[256];
        int i;

	try {
	    OutputStream out = socket.getOutputStream();
	    InputStream in = socket.getInputStream();

	    // get a set of bytes and process them
	    // call returns -1 for end-of-data
	    while ( ( dcount = in.read(data) ) > 0 )
	    {
		// properly, this should convert to string
		// convert it to uppercase (7-bit ASCII chars only)
                for( i=0; i<dcount; i++ )
		{
		    if ( (data[i] >= 97) && (data[i] <= 122) )
			data [i]-= 32;
		}

		// send it back
		out.write( data, 0, dcount );
	    }

	    out.close();
	    in.close();
	    socket.close();

	} catch (IOException e) {
	    e.printStackTrace();
	}
    }
}

public class ucase_j_ts {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        boolean listening = true;

        try {
            serverSocket = new ServerSocket(Integer.parseInt(args[0]));
        } catch (IOException e) {
            System.err.println("Could not listen on port: "+args[0] );
            System.exit(-1);
        }

        while (listening)
            new UcaseServerThread(serverSocket.accept()).start();

        serverSocket.close();
    }
}

Java UDP client

import java.io.*;
import java.net.*;

public class ucase_j_uc {
    public static void main(String[] args) throws IOException {

        try {
	    // create the UDP socket
	    DatagramSocket link = new DatagramSocket();

	    // hunt up the server
	    InetAddress server = InetAddress.getByName( args[0] );
	    int port = Integer.parseInt(args[1]);

	    // user input stream
	    BufferedReader stdIn =
			new BufferedReader(new InputStreamReader(System.in));

	    // one line from the user
	    String userInput;

	    // get data, send it to the server
	    while ((userInput = stdIn.readLine()) != null)
	    {
		// convert string to bytes
		byte[] b = userInput.getBytes();

		// create a UDP packet
		DatagramPacket pkt = new DatagramPacket(
			b, b.length, server, port );

		// send input to the server
		link.send( pkt );

		// get results from server
		byte[] RData = new byte[101];		// receive data buffer
		pkt = new DatagramPacket( RData, 100 );
		link.receive( pkt );

		// display result
		System.out.println( "echo: " +
			new String( RData, 0, RData.length) );
	    }

	    // done, do some cleanup
	    link.close();
	    stdIn.close();

        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: "+args[0]+".");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: " +
	    		args[0] + ".");
            System.exit(1);
        }


    }
}

Java UDP server

import java.io.*;
import java.net.*;

public class ucase_j_us {
    public static void main(String[] args) throws IOException {

        try {
	    // what port do we listen on?
	    int port = Integer.parseInt(args[0]);

	    // create the UDP socket
	    DatagramSocket link = new DatagramSocket( port );

	    // start working
	    while ( true )
	    {
		// get data  from client
		byte[] RData = new byte[101];		// receive data buffer
		DatagramPacket pkt = new DatagramPacket( RData, 100 );
		link.receive( pkt );

		// convert to a string
		String strdata = new String( RData, 0, RData.length );

		// convert uppercase string to bytes
                String udata = strdata.toUpperCase();
		byte[] b = udata.getBytes();

		// create a UDP packet
		DatagramPacket rpkt = new DatagramPacket(
			b, b.length, pkt.getAddress(), pkt.getPort() );

		// send result to the client
		link.send( rpkt );
	    }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: "+args[0]+".");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: " +
	    		args[0] + ".");
            System.exit(1);
        }
    }
}

Visual Studio .NET C++ example - I stopped after creating the TCP client because I found using the "managed" classes (which include system garbage collection) was nice but was really better suited for C# (below). The other alternative would have used the BSD socket calls, resulting in examples similar to the Linux C examples above.

Visual Studio .NET C++ TCP client

// client for the Ucase service
// for Visual Studio.net C++
// EFS 2/24/03

#using <mscorlib.dll>
#using <System.dll>
#include<iostream>
#include<vcclr.h>

using namespace std;

using namespace System;
using namespace System::Text;
using namespace System::Net;
using namespace System::Net::Sockets;

int main( int argc, char * argv[] )
{
    char curline[104];

    int port = atoi( argv[2] );
    cout << "Trying port " << port << "\n";

    try {
	// create a TCPclient object
	gcroot<TcpClient *> link = new TcpClient( argv[1], port );
	gcroot<Byte []> RecMsg = new Byte[100];
	int len;
	
	// get something we can talk with
	gcroot<NetworkStream *> stream = link->GetStream();

        // quietly ask for data
	cin.getline( &curline[0], 100 );

        while( strlen(curline) > 0 )
	{
		// make sure to add a "\n" to the end of the line
		// so Perl will be happy (Perl uses get_line!)
		strcat( curline, "\n" );

		// do some maniupation to keep the system happy
		gcroot<String *> strcurline = new String( curline );
		// send some data (data, offset, length)
		gcroot<Byte []> myWriteBuffer =
			Encoding::ASCII->GetBytes( strcurline );

		stream->Write(myWriteBuffer, 0, myWriteBuffer->Length);


		// get a response (buf, offset, len)
		len = stream->Read( RecMsg, 0, 100 );

		// display it
		for( int i=0; i<len; i++ )
			cout << (char)RecMsg[i];
		cout << "\n";
		
		// get another line
		cin.getline( &curline[0], 100 );
	}

	// close and exit
	link->Close();
    }
    catch (SocketException* e) {
	Console::WriteLine(S"SocketException: {0}", e);
    }


	exit(0);
}

Visual Studio .NET C# TCP command-line client

// client for the Ucase service
// for Visual Studio.net C#
// EFS 2/25/03
using System;
using System.Net;
using System.Net.Sockets;

class UcaseTcpClient
{
   public static void Main( string [] args )
   {
      // create a TCP client
      TcpClient link = new TcpClient( args[0], Int32.Parse(args[1]) );

      // get a stream for communication
      NetworkStream stream = link.GetStream();

      // quitely wait for data
      string message = Console.ReadLine();
      while( message.Length > 0 )
      {
         // convert to bytes for sending
         Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

         // send the data (buffer, offset, length)
         stream.Write( data, 0, data.Length );

         // prepare for a response
         data = new Byte[256];

         // string for ASCII version
         String responseData = String.Empty;

         // get the response
         Int32 bytecount = stream.Read( data, 0, data.Length );

         // convert back to a string
         responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytecount);
         Console.WriteLine("Received: {0}", responseData);

         // ask for more data
         message = Console.ReadLine();
      }

      // done!
      link.Close();
   }
}


Visual Studio .NET C# TCP graphical client

For the C# graphical client, I only included the .cs file corresponding to the form.
Here is a screenshot of the program:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;

namespace TCP_Client
{
	/// <summary>
	/// Implement a graphical UCASE TCP client
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox HostNameBox;
		private System.Windows.Forms.TextBox PortBox;
		private System.Windows.Forms.Button ConnectButton;
		private System.Windows.Forms.TextBox TextInput;
		private System.Windows.Forms.Label DisplayArea;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		// are we currently connected??
		bool AreConnected = false;

		// declare the TCP Client object we will use to communicate
		TcpClient link = null;
		private System.Windows.Forms.Button ProcessDataButton;

		// declare a stream for communication
		NetworkStream stream = null;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.label1 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.HostNameBox = new System.Windows.Forms.TextBox();
			this.PortBox = new System.Windows.Forms.TextBox();
			this.ConnectButton = new System.Windows.Forms.Button();
			this.TextInput = new System.Windows.Forms.TextBox();
			this.DisplayArea = new System.Windows.Forms.Label();
			this.ProcessDataButton = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(8, 8);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(32, 16);
			this.label1.TabIndex = 0;
			this.label1.Text = "Host";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 32);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(32, 16);
			this.label2.TabIndex = 1;
			this.label2.Text = "Port";
			// 
			// HostNameBox
			// 
			this.HostNameBox.Location = new System.Drawing.Point(48, 8);
			this.HostNameBox.Name = "HostNameBox";
			this.HostNameBox.Size = new System.Drawing.Size(112, 20);
			this.HostNameBox.TabIndex = 2;
			this.HostNameBox.Text = "";
			// 
			// PortBox
			// 
			this.PortBox.Location = new System.Drawing.Point(48, 32);
			this.PortBox.Name = "PortBox";
			this.PortBox.Size = new System.Drawing.Size(112, 20);
			this.PortBox.TabIndex = 3;
			this.PortBox.Text = "";
			// 
			// ConnectButton
			// 
			this.ConnectButton.Location = new System.Drawing.Point(176, 16);
			this.ConnectButton.Name = "ConnectButton";
			this.ConnectButton.Size = new System.Drawing.Size(96, 24);
			this.ConnectButton.TabIndex = 4;
			this.ConnectButton.Text = "Connect";
			this.ConnectButton.Click += new System.EventHandler(this.ConnectButton_Click);
			// 
			// TextInput
			// 
			this.TextInput.Location = new System.Drawing.Point(6, 64);
			this.TextInput.Name = "TextInput";
			this.TextInput.Size = new System.Drawing.Size(280, 20);
			this.TextInput.TabIndex = 5;
			this.TextInput.Text = "Type Text Here";
			// 
			// DisplayArea
			// 
			this.DisplayArea.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
			this.DisplayArea.Location = new System.Drawing.Point(6, 120);
			this.DisplayArea.Name = "DisplayArea";
			this.DisplayArea.Size = new System.Drawing.Size(280, 24);
			this.DisplayArea.TabIndex = 6;
			// 
			// ProcessDataButton
			// 
			this.ProcessDataButton.Enabled = false;
			this.ProcessDataButton.Location = new System.Drawing.Point(78, 88);
			this.ProcessDataButton.Name = "ProcessDataButton";
			this.ProcessDataButton.Size = new System.Drawing.Size(136, 24);
			this.ProcessDataButton.TabIndex = 7;
			this.ProcessDataButton.Text = "Convert to Uppercase";
			this.ProcessDataButton.Click += new System.EventHandler(this.ProcessDataButton_Click);
			// 
			// Form1
			// 
			this.AcceptButton = this.ProcessDataButton;
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(292, 149);
			this.Controls.Add(this.ProcessDataButton);
			this.Controls.Add(this.DisplayArea);
			this.Controls.Add(this.TextInput);
			this.Controls.Add(this.ConnectButton);
			this.Controls.Add(this.PortBox);
			this.Controls.Add(this.HostNameBox);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.label1);
			this.Name = "Form1";
			this.Text = "CSharp TCP Client";
			this.Load += new System.EventHandler(this.Form1_Load);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
		
		}

		private void ConnectButton_Click(object sender, System.EventArgs e)
		{
			// user has requested a connect or disconnect
			// are we currently connected?
			if ( ! AreConnected )
			{
				// not currently connected, do connect
				int portNumber = Int32.Parse( PortBox.Lines[0] );
				// create a TCP client
				link = new TcpClient( HostNameBox.Lines[0], portNumber );

				// get a stream for communication
				stream = link.GetStream();

				// note we are connected, change button
				AreConnected = true;
				ConnectButton.Text = "Disconnect";

				// allow user to process text
				ProcessDataButton.Enabled = true;
			}
			else
			{
				// are currently connected, disconnect
				link.Close();
				AreConnected = false;

				ConnectButton.Text = "Connect";

				// allow user to process text
				ProcessDataButton.Enabled = false;
				
				// don't need TcpClient, Stream anymore
				stream = null;
				link = null;
			}
		}

		private void ProcessDataButton_Click(object sender, System.EventArgs e)
		{
			// user wants to convert text to uppercase
			// and update the result

			// - be stupid and send the entire contents, even
			//		though there may only be a small change

			// get text to process
			string[] strdata = TextInput.Lines;

			// convert to bytes for sending
			Byte[] data = System.Text.Encoding.ASCII.GetBytes( strdata[0] );

			// send the data (buffer, offset, length)
			stream.Write( data, 0, data.Length );

			// prepare for a response
			data = new Byte[256];

			// string for ASCII version
			String responseData = String.Empty;

			// get the response
			Int32 bytecount = stream.Read( data, 0, data.Length );

			// convert back to a string and display it
			DisplayArea.Text = System.Text.Encoding.ASCII.GetString(data, 0, bytecount);
		
		}
	}
}

Visual Studio .NET C# TCP server

// server for the Ucase service
// for Visual Studio.net C#
// EFS 2/26/03
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;

// class to handle a thread
class UcaseClientThread
{
   // socket we use to talk to a client
   TcpClient sock;

   // initialization function
   public UcaseClientThread( TcpClient s )
		{ sock = s; }

   // processing function
   public void DoServer()
   {
      // define some variables we need later
      Byte [] data = new Byte[256];
      string strdata = null;
      Int32 i;

      // map to the corresponding network stream
      NetworkStream stream = sock.GetStream();

      // get data from the client
      while( ( i=stream.Read( data, 0, data.Length) ) != 0 )
      {
         // get it as a string
         strdata = System.Text.Encoding.ASCII.GetString( data, 0, i );

         // Convert to uppercase, back to BYTE so we can send it back
         data = System.Text.Encoding.ASCII.GetBytes( strdata.ToUpper() );

         // send it back
         stream.Write( data, 0, i );

         // clear buffers
         strdata = null;
         data = new Byte[256];
      }

      // done with this connection
      sock.Close();
   } // DoServer thread
} // UcaseClientThread class

// class to handle incoming requests and start up threads
class UcaseTcpServer
{
    public static void Main( string [] args )
    {
      // create a TCP socket for us to listen on
      TcpListener link = new TcpListener( IPAddress.Any, Int32.Parse(args[0]) );

      // ready for requests
      link.Start();

      // Wait for connection requests to arrive
      while( true )
      {

	 // Wait for a new incoming connection
	 TcpClient client = link.AcceptTcpClient();

	 // create an appropriate thread, pass it the client socket
	 UcaseClientThread child = new UcaseClientThread( client );

         Thread t = new Thread(new ThreadStart(child.DoServer));
	 // actually start the thread
         t.Start();

         // wait for a thread to finish
         //t.Join();
      }
   }
}

Visual Studio .NET C# UDP command-line client

// client for the Ucase service
// for Visual Studio.net C#
// EFS 2/25/03
using System;
using System.Net;
using System.Net.Sockets;

class UcaseUdpClient
{
   public static void Main( string [] args )
   {
      // create a TCP client
      UdpClient link = new UdpClient( args[0], Int32.Parse(args[1]) );

      // quitely wait for data
      string message = Console.ReadLine();
      while( message.Length > 0 )
      {
         // convert to bytes for sending
         Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

         // send the data (buffer, length)
         link.Send( data, data.Length );

         // prepare for a response
	 IPEndPoint RemoteIpEndPoint = new IPEndPoint( IPAddress.Any, 0 );

         // string for ASCII version
         String responseData = String.Empty;

         // get the response
	 data = link.Receive( ref RemoteIpEndPoint );

         // convert back to a string
         responseData = System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
         Console.WriteLine("Received: {0}", responseData);

         // ask for more data
         message = Console.ReadLine();
      }

      // done!
      link.Close();
   }
}

Visual Studio .NET C# UDP server

// server for the UDP Ucase service
// for Visual Studio.net C#
// EFS 2/26/03
using System;
using System.Net;
using System.Net.Sockets;

class UcaseUdpServer
{
   public static void Main( string [] args )
   {
      // create a UDP socket
      UdpClient link = new UdpClient( Int32.Parse(args[0]) );
      Byte[] data = null;

      // note client address
      IPEndPoint RemoteIpEndPoint = new IPEndPoint( IPAddress.Any, 0 );

      // wait for data to arrive
      while( true )
      {
	 // erase any previous stuff
	 data = null;

         // string for ASCII version
         String strdata = String.Empty;

         // get the messsage
         data = link.Receive( ref RemoteIpEndPoint );

         // convert to a string
         strdata = System.Text.Encoding.ASCII.GetString(
			 	data, 0, data.Length);

         // convert to uppercase, convert to bytes for sending
         data = System.Text.Encoding.ASCII.GetBytes(strdata.ToUpper());

         // send the data (buffer, length, address)
         link.Send( data, data.Length, RemoteIpEndPoint );
      }
   }
}

Go to the
CSC 460 Home Page
Go to My Home Page
Go to the Department of Computer Science Home Page
Go to the EKU Home Page