实现TCP协议需要有服务器端和客户端,java api提供了java.net包,为实现网络应用程序提供类
ServerSocket:为类实现服务器套接字
Socket:为类实现客户端套接字
Socket是网络驱动层提供给应用程序编程的接口和机制
实现服务器端和客户端程序
case:创建一个应答echo模型
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServerDemo {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(123);
System.out.println("Server is booting....");
//阻塞等待套接字的连接
Socket socket = server.accept();
System.out.println("Server has been connected!"+server.getInetAddress());
BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()));
//通过输入流读取网络数据
String info = br.readLine();
System.out.println(info);
//获取输出流,向客户端返回信息
PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
ps.println("echo:"+info);
ps.flush();
ps.close();
br.close();
}
}
import java.io.*;
import java.net.Socket;
public class EchoClientDemo {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost",123);
//获取socket的输入流和输出流
PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps.println("Start transporting....");
ps.flush();
String info = br.readLine();
System.out.println(info);
ps.close();
br.close();
}
}