testclient.java/* * Created on 2004-9-15 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ package socket;/** * @author Administrator * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ import java.net.*; import java.io.*;public class testclient { public static void main(String[] args) { Socket asocket; int i; DataOutputStream dos; byte[] buffer; while (true) { try { asocket = new Socket("127.0.0.1", 1500); dos = new DataOutputStream(asocket.getOutputStream()); buffer = new byte[512]; i = System.in.read(buffer); dos.write(buffer, 0, i); dos.close(); asocket.close(); } catch (Exception e) { System.out.println("client error"); } } } }
testserver.java/* * Created on 2004-9-15 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ package socket;/** * @author Administrator * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ import java.io.*; import java.net.*;public class testserver implements Runnable { public void run() { DataInputStream dis; Socket asocket; while (true) { try { ServerSocket aserver = new ServerSocket(1500); asocket = aserver.accept(); dis = new DataInputStream(asocket.getInputStream()); int read; byte[] buffer; do { buffer = new byte[512]; read = dis.read(buffer); String s = new String(buffer, 0, read); System.out.println(s); } while (read != -1); dis.close(); asocket.close(); } catch (Exception e) { System.out.println("server error"); } } } public static void main(String[] args) { Thread t1 = new Thread(new testserver()); t1.start(); }}
因简化原因,请看懂程序并作相应修改之后,才能运行。import java.io.*;
import java.net.*;
import java.util.*;public class ProtocolHandler { int listenPort = 8001;
ServerSocket myServer = null;
JuryThread checkIt;
Socket answerSocket; public ProtocolHandler()
{
try {
myServer = new ServerSocket(listenPort);
while (true) {
answerSocket = myServer.accept();
checkIt = new JuryThread(answerSocket);
checkIt.start();
}
}catch (Exception e) {}
}
public static void main(String args[]) {
new ProtocolHandler();
}
}
class JuryThread extends Thread {
Socket talkToMe;
ObjectOutputStream sendStream;
ObjectInputStream recvStream;
Command command;
boolean alive = true;
public JuryThread (Socket s){
talkToMe = s;
try {
OutputStream os = talkToMe.getOutputStream();
InputStream is = talkToMe.getInputStream();
sendStream = new ObjectOutputStream(os);
recvStream = new ObjectInputStream(is);
} catch (IOException e) {
}
}
public void run() {
while (alive) {
try {
System.out.println("reading object...");
command = (Command)recvStream.readObject();
System.out.println("object read.");
switch (command.getCommandValue())
{
case Command.READCUSTLIST:
{
...
break;
}
case Command.ADDACUSTOMER:
{
...
break;
}
} // end switch
sendStream.writeObject(command);
} catch (EOFException ex) {
//ex.printStackTrace();
System.out.println("Connection closed.");
alive = false;
} catch (SocketException ex){
//ex.printStackTrace();
System.out.println("Connection closed.");
alive = false;
} catch (Exception ex) {
ex.printStackTrace();
}
}// end while
} // end run
} // end JuryThread
* Created on 2004-9-15
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package socket;/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
import java.net.*;
import java.io.*;public class testclient
{
public static void main(String[] args)
{
Socket asocket;
int i;
DataOutputStream dos;
byte[] buffer;
while (true)
{
try
{
asocket = new Socket("127.0.0.1", 1500); dos = new DataOutputStream(asocket.getOutputStream());
buffer = new byte[512];
i = System.in.read(buffer);
dos.write(buffer, 0, i);
dos.close();
asocket.close(); }
catch (Exception e)
{
System.out.println("client error");
}
}
}
}
* Created on 2004-9-15
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package socket;/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
import java.io.*;
import java.net.*;public class testserver implements Runnable
{
public void run()
{
DataInputStream dis;
Socket asocket;
while (true)
{
try
{
ServerSocket aserver = new ServerSocket(1500); asocket = aserver.accept(); dis = new DataInputStream(asocket.getInputStream());
int read;
byte[] buffer;
do
{
buffer = new byte[512];
read = dis.read(buffer);
String s = new String(buffer, 0, read);
System.out.println(s);
}
while (read != -1);
dis.close();
asocket.close(); }
catch (Exception e)
{
System.out.println("server error");
}
}
} public static void main(String[] args)
{ Thread t1 = new Thread(new testserver());
t1.start(); }}
import java.net.*;
import java.io.*;class JabberClientThread extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private static int counter=0;
private int id=counter++;
private static int threadcount=0;
public static int threadCount(){
return threadcount;
}public JabberClientThread(InetAddress addr){
System.out.println("making client"+id);
threadcount++;
try{
socket=new Socket(addr, MultiJabberServer.PORT);
}catch(IOException e){
System.err.println("Socket Failed");
}
try{
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
start();
}catch(IOException e){
try{
socket.close();
}catch(IOException e2){
System.err.println("Scocket not closed");
}
}
}public void run(){
try{
for(int i=0;i<25;i++){
out.println("Client"+id+":"+i);
String str=in.readLine();
System.out.println(str);
}
out.println("END");
}catch(IOException e){
System.err.println("IO Exception");
}finally{
try{
socket.close();
}catch(IOException e){
System.err.println("Socket not closed");
}
threadcount--;
}
}
}public class MultiJabberClient{
static final int MAX_THREADS=40;
public static void main(String[] args)throws IOException,InterruptedException{
InetAddress addr=InetAddress.getByName(null);
while(true){
if(JabberClientThread.threadCount()<MAX_THREADS)new JabberClientThread(addr);
Thread.currentThread().sleep(100);
}
}
}
//服务器端
import java.io.*;
import java.net.*;class ServeOneJabber extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ServeOneJabber(Socket s) throws IOException{
socket=s;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
start();
} public void run(){
try{
while(true){
String str = in.readLine();
if (str.equals("END")) break;
System.out.println("Echoing:" + str);
out.println(str);
}
System.out.println("closing...");
}catch(IOException e){
System.err.println("IO Exception");
}finally{
try{
socket.close();
}catch(IOException e){
System.err.println("Socket not closed");
}
}
}
} public class MultiJabberServer{
static final int PORT=8080;
public static void main(String[] args)throws IOException{
ServerSocket s=new ServerSocket(PORT);
System.out.println("Server Started");
try{
while(true){
Socket socket=s.accept();
try{
new ServeOneJabber(socket);
}catch(IOException e){
socket.close();
}
}
}finally{
s.close();
}
}
}
//这个程序我调试通过的,你自己仔细看懂哦,希望可以帮上你.
简单的服务器这个服务器所做的全部工作是在留式连接上发送字符串 "Hello, World!\n"。你要 测试这个程序的话,可以在一台机器上运行该程序,然后在另外一机器上登陆: $ telnet remotehostname 3490remotehostname 是该程序运行的机器的名字。服务器代码: #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> #define MYPORT 3490 /* the port users will be connecting to */ #define BACKLOG 10 /* how many pending connections queue will hold */ main() { int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd */ struct sockaddr_in my_addr; /* my address information */ struct sockaddr_in their_addr; /* connector's address information */ int sin_size; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } my_addr.sin_family = AF_INET; /* host byte order */ my_addr.sin_port = htons(MYPORT); /* short, network byte order */ my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */ bzero(&(my_addr.sin_zero), 8); /* zero the rest of the struct */ if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) \ == -1) { perror("bind"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while(1) { /* main accept() loop */ sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \ &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n", \ inet_ntoa(their_addr.sin_addr)); if (!fork()) { /* this is the child process */ if (send(new_fd, "Hello, world!\n", 14, 0) == -1) perror("send"); close(new_fd); exit(0); } close(new_fd); /* parent doesn't need this */ while(waitpid(-1,NULL,WNOHANG) > 0); /* clean up child processes */ } }如果你很挑剔的话,一定不满意我所有的代码都在一个很大的 main() 函数 中。如果你不喜欢,可以划分得更细点。你也可以用我们下一章中的程序得到服务器端发送的字符串。