简单的Java C/S模式
(TCP协议下C/S模式)
TCP通信原理流程
客户端:
a、用服务器的IP地址和端口号实例化Socket对象;
b、调用connect方法,连接到服务器上;
c、将发送到服务器的I/O流填充到I/O对象里,比如BufferedReader/PrintWriter;
d、利用Socket提供的getInputStream和getOutputStream方法,通过I/O流对象,向服务器发送数据流;
e、通信完成后,关闭打开的I/O对象和Socket。
服务器:
a、 用一个端口实例化一个ServerSocket对象
b、 调用ServerSocket的accept(public Socket accept())方法,开始监听连接从端口上发来的连接请求;
c、 利用accept方法返回的客户端的Socket对象,进行读写I/O的操作;
d、 通信完成后,关闭打开的流和Socket对象。
eg:(先运行服务器端,再运行客户端)
客户端:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class ClientCode {
static String clientName = "Mike";
//端口号
public static int portNo = 3333;
/**
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) throws IOException {
//设置连接地址类,连接本地
InetAddress addr = InetAddress.getByName("localhost");
//要对应服务器端的3333端口号
Socket socket = new Socket(addr, portNo);
try {
System.out.println("socket= "+socket);
BufferedReader in = 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 = in.readLine();
System.out.println(str+"yuy");
out.println("byebye");
}finally{
System.out.println("close the Client socket and the io.");
socket.close();
}
}
}
服务器端
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerCode {
/**
* @param args
*/
//设置端口号
public static int portNo = 3333;
public static void main(String[] args) throws IOException {
//根据端口号,初始化ServerSocket类
ServerSocket s = new ServerSocket(portNo);
System.out.println("The Server is start:"+s);
//阻塞,直到有客户端连接(监听从客户端的连接请求)
Socket socket = s.accept();
try {
System.out.println("Accept the Client:"+socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
while(true){
String str = in.readLine();
//如果接受到byebye字符串,退出循环
if(str.equals("byebye"))
break;
System.out.println("In Server reveived the info: "+str);
out.println(str);
}
} finally{
System.out.println("close the Server socket and the io.");
//关闭socket
socket.close();
s.close();
}
}
}