PS.println(s); //将读取得字符串传给client
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
}
//关闭连接
DIS.close(); //关闭数据输入流
PS.close(); //关闭数据输出流
Is.close(); //关闭输入流
Os.close(); //关闭输出流
socket.close(); //关闭sockey
}
catch(Exception e){
System.out.println("Error:"+e);
}
}
}
通话器客户端
import java.net.*;
import java.io.*;
import java.lang.*;
public class myclient{
public static void main(String args[]){
if (args.length<1){ //判断命令加参数没有
System.out.println("you forget the name of the server!");
System.out.println("see also: myclient yxf");
System.exit(1); //如果没加参数就退出
}
Socket socket;
String s="yxfsoft@263.net";
String len;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;
try{
//向主机名为args[0]的服务器申请连接
//注意端口号要与服务器保持一致:4321
socket=new Socket(args[0],4321);
System.out.println("client ok");
System.out.println("************************************************");
System.out.println("");
//获得对应socket的输入/输出流
Is=socket.getInputStream();
Os=socket.getOutputStream();
//建立数据流
DIS=new DataInputStream(Is);
PS=new PrintStream(Os);
DataInputStream in=new DataInputStream(System.in);
while(true){
System.out.print("you say:");
s=in.readLine(); //读取用户输入的字符串
PS.println(s); //将读取得字符串传给server
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
else
{
System.out.println("");
System.out.println("please wait server's message...");
System.out.println("");
}
s=DIS.readLine(); //从服务器获得字符串
System.out.println("server said:"+s); //打印字符串
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
}
//关闭连接
DIS.close(); //关闭数据输入流
PS.close(); //关闭数据输出流
Is.close(); //关闭输入流
Os.close(); //关闭输出流
socket.close(); //关闭socket
}
catch(Exception e){
System.out.println("Error:"+e);
}
}
}
下载源文件:客户端工程,服务器工程。编程环境为VisualJ++6.0。
请读者先在一台机器上运行myserver.exe(myserver.exe在服务器工程内),然后在同一台机器或与第一台机器连了网的机器上打开控制台(Dos窗口),然后转到myclient.exe(myclient.exe在客户端工程内)所在的目录,如下运行客户端程序: myclient serverhostName 或 myclient serverhostIp ,serverhostName为运行服务器程序的机器名, serverhostIp为运行服务器程序的机器的IP地址。运行后就可以相互通话了。这个通话程序只能轮换着说话,读者可以在它的基础上丰富其功能。
原作者:小锋
【问题提问、论坛交流】编辑:xker.com

发表评论