---------------- client.c ----------------------------------------
#>:cat client.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netdb.h>
#include <resolv.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAXBUF 1024
int main(int argc, char **argv)
{
int sockfd, len;
struct hostent *host = NULL;
struct sockaddr_in dest;
if (argc != 3) {
printf("Usage: %s address port/n",argv[0]);
exit(0);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Socket");
exit(errno);
}
bzero(&dest, sizeof(dest));
host = gethostbyname(argv[1]);
if (host == NULL)
{
perror("Socket");
exit(errno);
}
dest.sin_family = AF_INET;
dest.sin_port = htons(atoi(argv[2]));
//dest.sin_addr.s_addr = inet_addr(argv[1]);
memcpy(&dest.sin_addr, host->h_addr, host->h_length);
if (connect(sockfd, (struct sockaddr *) &dest, sizeof(dest)) != 0) {
perror("Connect");
exit(errno);
}
char buffer[MAXBUF + 1];
bzero(buffer, MAXBUF + 1);
strcpy(buffer, "GET");
len = send(sockfd, buffer, strlen(buffer), 0);
if (len < 0)
printf("send message '%s' failed, with error code: %d, error message:'%s'./n",
buffer, errno, strerror(errno));
else
printf("send message '%s' succeed, send length is %d./n", buffer, len);
bzero(buffer, MAXBUF + 1);
len = recv(sockfd, buffer, MAXBUF, 0);
if (len > 0)
printf("receive message '%s' success, total %d bytes data/n", buffer, len);
else
printf("receive message failed, with error code: %d, error message: '%s'./n",
errno, strerror(errno));
close(sockfd);
return 0;
}
---------------- server.c ----------------------------------------
#>:cat server.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <arpa/inet.h>
#define MAXBUF 1024
int main(int argc, char **argv)
{
int sockfd, new_fd;
socklen_t len;
struct sockaddr_in my_addr, their_addr;
unsigned int myport, lisnum;
char buf[MAXBUF + 1];
if (argc != 2) {
printf("Usage %s port/n",argv[0]);
exit(0);
}
myport = atoi(argv[1]);
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
else printf("socket created/n");
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = PF_INET;
my_addr.sin_port = htons(myport);
//my_addr.sin_addr.s_addr = inet_addr(argv[3]);
my_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
else printf("binded/n");
if (listen(sockfd, lisnum) == -1) {
perror("listen");
exit(1);
}
else printf("begin listen/n");
while(1) {
len = sizeof(struct sockaddr);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &len)) == -1) {
perror("accept");
exit(errno);
}
else
printf("server: got connection from %s, port %d, socket %d/n",inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port), new_fd);
/*
bzero(buf, MAXBUF + 1);
strcpy(buf, "/n");
len = send(new_fd, buf, strlen(buf), 0);
if(len < 0) {
printf("'%s',%d,'%s'/n", buf, errno, strerror(errno));
}
else printf("'%s',%d/n", buf, len);
bzero(buf, MAXBUF + 1);
len = recv(new_fd, buf, MAXBUF, 0);
if(len > 0) printf("'%s'%d/n", buf, len);
else printf("%d'%s'/n", errno, strerror(errno));
*/
}
close(sockfd);
return 0;
}
# cc client.c -o client -lsocket -lnsl
# cc server.c -o server -lsocket -lnsl
# 要实现非阻塞通信方式, 可以参考系统调用select/poll的用法, http://bbs2.chinaunix.net/archiver/tid-1326519.html
---------------- Client.java ----------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client
{
/**
* Usage:
* $> program host port
* @param args
*/
public static void main(String[] args) {
if (args.length != 2)
{
System.out.println("Usage:/n/t$> program host port");
System.exit(0);
}
String host = args[0];
int port = Integer.parseInt(args[1]);
Socket s = null;
try {
s = new Socket (host, port);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//InputStreamReader isr = null;
BufferedReader reader = null;
PrintWriter writer = null;
try {
reader = new BufferedReader (new InputStreamReader (s.getInputStream ()));
writer = new PrintWriter (s.getOutputStream (), true);
BufferedReader cmdReader = new BufferedReader (new InputStreamReader (System.in));
String sent = null;
while(true)
{
System.out.print("message(q,quit)> ");
sent = cmdReader.readLine();
if (sent.equals("q") || sent.equals("quit"))
break;
if (sent.length() <= 0)
continue;
//System.out.println("send message: " + sent);
writer.println(sent);
String received = reader.readLine ();
if (received != null) {
System.out.println("receive message: " + received);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println ("Closing Connection.../n");
try {
reader.close();
writer.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
---------------- Server.java ----------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Calendar;
class Server {
public static void main(String[] args) throws IOException {
System.out.println("Server starting.../n");
ServerSocket server = new ServerSocket(10000);
while (true) {
Socket s = server.accept();
System.out.println("Accepting Connection.../n");
SocketAddress ra = s.getRemoteSocketAddress();
SocketAddress la = s.getLocalSocketAddress();
InetSocketAddress ria = (InetSocketAddress) ra;
InetSocketAddress lia = (InetSocketAddress) la;
System.out.println("Local Address:"+lia.getAddress()+":"+lia.getPort());
System.out.println("Remote Address:"+ria.getAddress()+":"+ria.getPort());
// Start a thread to handle the connection.
new ServerThread(s).start();
}
}
}
class ServerThread extends Thread {
private Socket s;
ServerThread(Socket s) {
this.s = s;
}
public void run ()
{
BufferedReader reader = null;
PrintWriter writer = null;
try
{
reader = new BufferedReader (new InputStreamReader (s.getInputStream ()));
writer = new PrintWriter (s.getOutputStream (), true);
do
{
String cmd = reader.readLine ();
if (cmd != null) {
System.out.println("Receive message: [" + cmd + "], send back with double.");
writer.println (cmd+":"+cmd);
} else {
break;
}
} while (true);
// System.out.println("Need to quit.");
} catch (IOException e) {
System.out.println ("Exception : " + e.toString ());
} finally {
System.out.println ("Closing Connection.../n");
try
{
if (reader != null)
reader.close ();
if (writer != null)
writer.close ();
if (s != null)
s.close ();
} catch (Exception e){}
}
} // run
}