C/S结构(Client/Server)客户端+服务器端,一般分TCP和UDP两种
B/S结构(Browser/Server)浏览器+服务器端,使用HTTP协议
以下介绍C/S中的TCP实现,Java Socket通信
ServerSocket
TCP协议操作类,主要用在服务器端,用于接收客户端请求
ServerSocket(int port)构造方法
accept()接收客户端请求,返回Socket
close()关闭服务端
Socket
TCP协议操作类,主要用在客户端,表示一个客户端
Socket(String host,int port)构造方法(host填IP地址,localhost代表本机ip:127.0.0.1)
getOutputStream()用于输出数据,获取OutputStream对象
getInputStream()用于读取数据,获取InputStream对象
示例代码:最简单的一个客户端和服务器端
public class ServiceTest1 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(9999);
System.out.println("等待客户端连接");
Socket socket=serverSocket.accept();
PrintStream printStream=new PrintStream(socket.getOutputStream());
printStream.println("hello world");
printStream.println("测试Socket通信");
printStream.close();
socket.close();
serverSocket.close();
System.out.println("连接完毕,停止通信");
}
}
public class ClientTest1 {
public static void main(String[] args) throws IOException {
Socket socket=new Socket("localhost",9999);
Scanner scanner=new Scanner(socket.getInputStream());
scanner.useDelimiter("\n");
while (scanner.hasNext()){
System.out.println(scanner.next());
}
scanner.close();
socket.close();
}
}
示例代码:经典Echo网络模型,增加了多线程支持多个客户端连接
服务器端的Runnable类
public class EchoThreadTest2 implements Runnable{
private Socket socket;
public EchoThreadTest2(Socket socket){
this.socket=socket;
}
@Override
public void run() {
try {
Scanner scanner=new Scanner(socket.getInputStream());
PrintStream printStream=new PrintStream(socket.getOutputStream());
boolean flag=true;
while (flag){
if (scanner.hasNext()){
String str=scanner.next().trim();
if (str.equalsIgnoreCase("byebye")){
printStream.println("拜拜,断开连接");
flag=false;
}else {
printStream.println("Echo:"+str);
}
}
}
scanner.close();
socket.close();
printStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器端
public class ServiceTest2 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(9999);
boolean flag=true;
int number=0;
while (flag){
number++;
Socket socket=serverSocket.accept();
new Thread(new EchoThreadTest2(socket)).start();
System.out.println(number);
}
}
}
客户端
public class ClientTest2 {
public static void main(String[] args) throws IOException {
Socket socket=new Socket("localhost",9999);
Scanner input=new Scanner(System.in);
Scanner scanner=new Scanner(socket.getInputStream());
input.useDelimiter("\n");
scanner.useDelimiter("\n");
PrintStream printStream=new PrintStream(socket.getOutputStream());
boolean flag=true;
while (flag){
System.out.println("请输入要发送的数据:");
if (input.hasNext()){
String str=input.next().trim();
printStream.println(str);
if (str.equalsIgnoreCase("byebye")){
flag=false;
}
if (scanner.hasNext()){
System.out.println(scanner.next());
}
}
}
scanner.close();
socket.close();
input.close();
printStream.close();
}
}
打印日志