网络编程实现客户机/服务器一对一通信模型,是在NetBeans IDE上进行操作的
【服务器代码】
package cn.edu.ldu;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
public class EchoServer {
public static void main(String[] args) throws IOException {
ServerSocket listenSocket=null;
Socket clientSocket=null;//会话套接字
BufferedReader in=null;//网络输入输出流
BufferedWriter out=null;
//1.启动服务器
listenSocket=new ServerSocket();
SocketAddress serverAddr=new InetSocketAddress("localhost",5000);
listenSocket.bind(serverAddr);
System.out.println("1.服务器启动成功");
//2.接受连接
clientSocket=listenSocket.accept();
System.out.println("2.服务器开始接受客户机链接...远程地址端口"
+clientSocket.getRemoteSocketAddress());
//3.创建输入输出流
in=new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
out=new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream()));
String recvStr=in.readLine();//服务器接收数据
System.out.println("3.1 服务器接收了来自客户机的:"+recvStr);
out.write(recvStr);
out.newLine();
out.flush();
System.out.println("3.2服务器回送了:"+recvStr);
//4.关闭流和套接字
if(in!=null)
in.close();
if(out!=null)
out.close();
if(clientSocket!=null)
clientSocket.close();
if(listenSocket!=null)
listenSocket.close();
System.out.println("4.服务器关闭了套接字和流!运行结束");
}
}
【客户机代码】
package cn.edu.ldu;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket clientSocket=null;//会话套接字
BufferedReader in=null;//网络输入输出流
BufferedWriter out=null;
//1.启动客户机会话套接字
clientSocket=new Socket();
SocketAddress remoteAddr=new InetSocketAddress("localhost",5000);
System.out.println("1.创建客户机会话套接字成功");
//2.连接服务器
clientSocket.connect(remoteAddr);
System.out.println("2.客户机连接服务器成功!本地使用的地址端口:"
+clientSocket.getLocalSocketAddress());
//3.创建输入输出流
in=new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
out=new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream()));
String sendStr="有朋自远方来!";
out.write(sendStr);
out.newLine();
out.flush();
System.out.println("3.1客户机发送了:"+sendStr);
String recvStr=in.readLine();
System.out.println("3.2 客户机收到了服务器的回送信息:"+recvStr);
//4.关闭流和套接字
if(in!=null)
in.close();
if(out!=null)
out.close();
if(clientSocket!=null)
clientSocket.close();
System.out.println("4.服务器关闭了套接字和流!运行结束");
}
}