一个c-s结构的java程序

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

//MiniServer.java - server that echos what it receives 服务器端

import java.io.*;

import java.net.*;

class Server{

public static void main (String args[])

throws java.io.IOException

{ byte A[]=new byte[10];

if (args.length != 1) {

System.out.println("Usage: " +

"java MiniServer portnumber");

System.exit(1);

}

int portnum = Integer.parseInt(args[0]);

ServerSocket sock = null;

try {

sock = new ServerSocket(portnum);

}

catch (IOException e) {

System.out.println("不能监听端口: "

+ portnum + ", " + e);

System.exit(1);

}

System.out.println("正在监听端口 " +

portnum);

Socket clientSocket = null;

try {

clientSocket = sock.accept();

}

catch (IOException e) {

System.out.println("接收失败: " +

portnum + ", " + e);

System.exit(1);

}

BufferedReader input = new BufferedReader(

new InputStreamReader(

clientSocket.getInputStream()));

PrintWriter output =

new PrintWriter(clientSocket.getOutputStream());

System.out.println("连接存在.");

int i = 0;

String line = input.readLine();

System.in.read(A);

String link = new String(A);

while (link!=null) {

System.out.println(line);

i++;

output.println("line " + i + ":" + link);

output.flush();

System.in.read(A);

link= new String(A);

}

}

}

********************************************

//MiniClient.java - simple client for MiniServer 客户端

import java.io.*;

import java.net.*;

class Telnet{

public static void main (String args[])

throws java.io.IOException

{ byte b[]=new byte[10];

if (args.length != 2) {

System.out.println("提示: " +"使用 Telnet IP PortNum 来测试你的程序 如 Telnet 127.0.0.1 8080");

System.exit(0);

}

Socket sock= null;

int portnum = Integer.valueOf(args[1]).intValue();

try {

sock = new Socket(args[0], portnum);

}

catch (IOException e) {

System.out.println("不能连接: "+args[0]+":"+portnum + ", " + e);

System.exit(1);

}

BufferedReader input = new BufferedReader(

new InputStreamReader(sock.getInputStream()));

PrintWriter output =

new PrintWriter(sock.getOutputStream());

System.out.println("连接已经建立");

System.out.println("请输入讯息" +

" 并按回车:");

System.in.read(b);

String line = new String(b);

while (line != null) {

output.println(line);

output.flush();

line = input.readLine();

System.out.println("服务器返回讯息:" + line);

System.out.println("请输入讯息 " +

"并按回车:");

System.in.read(b);

line = new String(b);

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航