⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 java语言的socket编程.txt

📁 含有许多JAVA的技巧!
💻 TXT
📖 第 1 页 / 共 2 页
字号:
StringBuffer buf = new StringBuffer(50);

int c;

String fromServer,usertyped;

while ((fromServer = client_in.readLine()) != null) {

System.out.println("Server: " + fromServer);

while ((c = System.in.read()) != '\n') {

buf.append((char)c);

}

usertyped=buf.toString();

client_out.println(usertyped);

client_out.flush();

buf.setLength(0);

}

} catch (Exception e) {

System.out.println(e);

}

}

}

该程序与前面的程序类似,不同之处在于该程序使用循环:

while ((fromServer = client_in.readLine()) != null) {

...}

反复读取服务端的输入,并用:

while ((c = System.in.read()) != '\n') {

buf.append((char)c);

}

usertyped=buf.toString();

client_out.println(usertyped);

语句读取用户的键盘输入,发送至服务端。其对话如下所示:

客户端

C:\xyx\java\sock\bak\ftp>java ftpc

Server: Welcome to the test server

anonymous

Server: 331 Please send Password

xyx@yc.shu.edu.cn

Server: 230 Login OK

bye

服务端

C:\xyx\java\sock\bak\ftp>java ftpserver

got follow infor from client:anonymous

got follow infor from client:xyx@yc.shu.edu.cn

got follow infor from client:bye

值得一提的是,该客户软件不仅可以和前面的模拟FTP服务器进行通讯,而且可以和真正的FTP服务器通讯。如将该客户软件中IP地址“202.120.127.201”改为某FTP服务器的IP地址:“202.120.127.218”,则可作如下的通讯:

C:\xyx\java\sock\bak\ftp>javac ftpc

Server: 220 sun1000E-1 FTP server (UNIX(r) System V Release 4.0) ready.

USER anonymous

Server: 331 Guest login ok, send ident as password.

PASS xyx@yc.shu.edu.cn

Server: 230 Guest login ok, access restrictions apply.

QUIT

Server: 221 Goodbye.

其中,USER、PASS、QUIT分别为协议规定的用户帐号、口令及退出的命令。

四、处理客户端请求

以上的例子均只在服务端与客户端相互传送信息,在实用中,服务端应能对客户端不同的输入作出不同的响应。本节给出一个服务端处理客户端请求的例子,协议如下:客户连接后,服务端发送“Welcome to Time server”信息,客户端读取用户输入发送给服务端,如果客户端输入为Hours,则发送当前小时数至客户端;如果客户端输入为Minutes、Years、Month、Day、Time、Date、down,则分别发送分钟数、年份、月份、日期、时分秒、年月日至客户端;客户端输入down则结束会话。

其客户端仍采用上一节编写的模拟FTP服务器的客户程序,但需将程序中的端口21改为8885,以便与下面的服务端程序对话。服务端的程序修改如下:

import java.net.*;

import java.io.*;

import java.util.Date;

class server {

public static void main(String args[])

{ try {

ServerSocket server_Socket = new ServerSocket(8885);

Socket client_Socket = server_Socket.accept();

DataInputStream server_in = new DataInputStream(client_Socket.getInputStream());

PrintStream server_out = new PrintStream(client_Socket.getOutputStream());

String inputLine, outputLine;

server_out.println("Welcome to Time server");

server_out.flush();

Date t=new Date();

while ((inputLine = server_in.readLine()) != null) {

System.out.println("got"+inputLine);

String hours = String.valueOf(t.getHours());

String minutes = String.valueOf(t.getMinutes());

String seconds = String.valueOf(t.getSeconds());

String years = String.valueOf(t.getYear());

String month = String.valueOf(t.getMonth());

String day = String.valueOf(t.getDay());

if(inputLine.equalsIgnoreCase("Down"))

break;

else if(inputLine.equalsIgnoreCase("Hours"))

server_out.println("Current Hours is:"+hours);

else if(inputLine.equalsIgnoreCase("Minutes"))

server_out.println("Current Minutes is:"+minutes);

else if(inputLine.equalsIgnoreCase("Years"))

server_out.println("Current Years is:"+years);

else if(inputLine.equalsIgnoreCase("Month"))

server_out.println("Current Month is:"+month);

else if(inputLine.equalsIgnoreCase("Day"))

server_out.println("Current Day is:"+day);

else if(inputLine.equalsIgnoreCase("Time"))

server_out.println("Current Times is:"+hours+":"+minutes+":"+seconds);

else if(inputLine.equalsIgnoreCase("Date"))

server_out.println("Current Date is:"+years+"."+month+"."+day);

else server_out.println("I don't know");

server_out.flush();

}

}

catch(Exception e){

System.out.println(e);

}

}

}

在该程序中,使用类似前面客户端的方法,用一个循环

while ((inputLine = server_in.readLine()) != null) {

...}

反复读取客户端的信息。在循环中根据客户端传来的不同信息作不同的处理。

五、程序的优化

为了使程序更优化,可从以下方面入手:

1. 进行出错处理

如可对每句使用try{...}catch(...){...}的形式处理程序中的例外情况,恰当地返回出错信息或进行出错处理等。

2. 关闭打开的Socket和流

结束对话时将所打开的Socket和流都关闭,Java中的SeverScoket、Socket、DataInputStream及DataOutputStream类都提供了方法close()来实现此功能。

3. 支持多次连接

前面的服务端程序在结束一次对话后都将自动结束,如果再有客户端要建立连接需要重新执行服务端的程序。为了使服务端支持多次连接,只要用一个循环即可。如对前面所有的服务端程序,都可以将执行“accept()”的语句至“}catch(Exception e)”语句的前一行包含在while(true){...}的循环体中而使其支持多次连接。

4. 使用线程

服务端程序一般使用线程,以便在等待客户端连接时可以处理其他事情。此外,通过为每个客户端的请求分配一个新的线程,可以使服务端能够同时支持多个连接,并行处理客户端的请求。

〖参考资料〗

1. Mary Campione and Kathy Walrath, 

"The Java Tutorial", 

last updated 4 Mar 96.

ftp://ftp.javasoft.com/docs/tutorial.html.zip

2. Laura Lemay, 

Charles L. Perkins, 

"Teach Yourself JAVA in 21 Days"

3. "The Java Language Tutorial" 

ftp://java.sun.com/docs/progGuide.html.zip 

4. elharo@sunsite.unc.edu, 

"Brewing Java: A Tutorial", 

Last-modified: 1996/9/20,

http://sunsite.unc.edu/javafaq/javatutorial.html

本栏文章均来自于互联网,版权归原作者和各发布网站所有,本站收集这些文章仅供学习参考之用。任何人都不能将这些文章用于商业或者其他目的。( ProgramFan.Com )
 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -