客户端与服务器端的简单通信实例
程序员文章站
2024-03-23 10:06:40
...
一、提前储备知识
1.PrintWriter类详解:(java.io.PrintWriter是java中很常见的一个类,该类可用来创建一个文件并向文本文件写入数据。可以理解为java中的文件输出,java中的文件输入则是java.io.File)
2.BufferedReader 字符输入缓冲类:(从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。)
二、client
在了解 TCP 通信中 ServerSocket 类和 Socket 类的简单应用之后,本节将编写一个案例实现客户端向服务器发送信息,服务器读取客户端发送的信息,并将读取的数据写入到数据流中。
package com.tcpcssocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SimpleSocket {
public static void main(String[] args) {
//client
Socket sot = null;
//output in file,read in program
BufferedReader inB = null;
//input in file,write in program
PrintWriter outP = null;
String serverIP = "127.0.0.1";
int port = 5000;
try {
//create link = instantiation
sot = new Socket(serverIP,port);
//packing
inB = new BufferedReader(new InputStreamReader(sot.getInputStream()));
outP = new PrintWriter(sot.getOutputStream(),true);
while (true) {
//random-math
int munber = (int)(Math.random()*10+1);
System.out.println("客户端正在发送的内容:" +munber);
outP.println(munber);
//thread-sleep,stand-by
Thread.sleep(2000);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
三、server
package com.tcpcssocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.InflaterInputStream;
public class SimpleServerSocket {
public static void main(String[] args) {
//server
ServerSocket sst = null;
Socket sot = null;
BufferedReader inB = null;
int port = 5000;
String str = null;
try {
//create server-socket,and instantiation
sst = new ServerSocket(port);
System.out.println("开启服务器并且等待连接:");
sot = sst.accept();
//acquire client-massage
inB = new BufferedReader(new InputStreamReader(sot.getInputStream()));
while (true) {
str = inB.readLine();
System.out.println("客户端发送的内容为:" +str);
Thread.sleep(2000);
}
// 运行.....,不可close();
/* sst.close();
sot.close();
inB.close();*/
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
上一篇: 用wihle实现一个乘法表
下一篇: makefile--宏控制