实验要求:
1.编写基于TCP协议的通信程序,包括Server与Client两个部分。实现回声程序:即客户端发送消息,服务器端将收到的消息原样会送给客户端。
2.在单机上运行它们,验证其通信结果;
3.在多机上运行它们,验证其通信结果;(ChatServer只需运行在一台主机上,ChatClient可在其它主机上运行(要知道ChatServer所在主机的IP地址)。
4.提示:服务器端回送消息时,可以进行加工,例如给每个收到的消息加上“服务器回送”+原始消息+服务器端收到消息的时间;
5.客户端可以从4字节数据开始发送,逐渐增大数据量,观察从少量数据的发送到大量数据的发送,时间性能的变化,记录每次发送数据所需时间,利用excel制作曲线图(该部分实验可选)
源码:
服务器端:
package tcpipchapter3;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class server {
/**
* @param args
*/
//设置端口号/
public static int portNo=3333;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//初始化serverSocket类
ServerSocket s=new ServerSocket(portNo);
System.out.println("The Server is starting...");
//建立socket连接(阻塞,直到有客户端连接)
Socket socket=s.accept();
//接收数据
try{
//构造输入流缓存
BufferedReader bufReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
String time=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date());
while(true){
//按行读取输入内容
String strLine=bufReader.readLine();
//如果收到byebye则退出循环
if(strLine.equals("byebye")){
break;
}
System.out.println("In the Server reveived the info: "+strLine);
//向客户端发送接收到的数据
System.out.println("The server is send the received msg to the client...");
out.println("The received msg is: "+strLine+" and The time is:"+time);
}
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("close the Server socket and the io");
//关闭socket,断开连接
socket.close();
s.close();
}
}
}
客户端:
package tcpipchapter3;
import java.io.*;
import java.net.*;
public class client {
/**
* @param args
*/
public static String clientName="laughcry";
//设置端口号
public static int portNo=3333;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//设置连接地址类,连接本地,描述使用本socket的ip地址
InetAddress addr=InetAddress.getByName("localhost");
//初始化socket类
Socket socket=new Socket(addr,portNo);
try{
System.out.println("socket="+socket);
//设置io句柄
BufferedReader bufReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
//向服务器端发送数据
out.println("Hello server ,I am "+clientName);
//接受服务器返回的信息
String str=bufReader.readLine();
System.out.println("The msg from server is: "+str);
out.println("byebye");
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭连接
System.out.println("close the client socket and the io.");
socket.close();
}
}
}