Java案例——TCP通信程序
需求:
- 客户端:发送数据,数据来自于文本文件,接收服务器反馈。
- 服务器:接收到的数据写入文本文件,给出反馈,代码用线程进行封装,为每一个客户端开启一个线程。
代码实现(先运行服务端,再运行客户端):
package TCPPackage;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TestClient {
public static void main(String[] args) throws IOException {
//创建客户端的Socket对象(Socket);
//Socket(InetAddress address, int port):创建流套接字并将其连接到指定IP地址的指定端口号
Socket s = new Socket(InetAddress.getByName("192.168.0.103"), 20000);
//Socket(String host, int port):创建流套接字并将其连接到指定主机的指定端口号
//Socket s = new Socket("192.168.0.103",20000);
//1、数据来自键盘录入,直到输入的数据是886,发送数据结束
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//2、数据来自文本文件
BufferedReader br = new BufferedReader(new FileReader("F:\\javaFT\\send.txt"));
//封装输出流对象
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line;
while ((line = br.readLine()) != null) {
/*方式1的代码块:
if (line.equals("886")) {
break;
}
*/
//获取输出流,写数据;
//OutputStream getOutputStream():返回此套接字的输出流
//OutputStream os = s.getOutputStream();
//os.write(line.getBytes());
bw.write(line);
bw.newLine();
bw.flush();
}
//Socket提供的方法,给出结束标记(自定义结束标记可能会出问题)
//public void shutdownOutput()
s.shutdownOutput();
//接收服务器反馈
BufferedReader brFeedbacked = new BufferedReader(new InputStreamReader(s.getInputStream()));
String strData = brFeedbacked.readLine();
System.out.println("客户端得到的反馈:" + strData);
//释放资源。
br.close();
// is.close();
// os.close();
s.close(); //is 和 os 是根据s创建的,因此关闭s即可
}
}
package TCPPackage;
import java.io.*;
import java.net.Socket;
public class ServerThread implements Runnable{
private Socket s;
public ServerThread(Socket s){
this.s = s;
}
@Override
public void run() {
try{
//解决名称冲突问题
int count = 0;
File file = new File("F:\\javaFT\\recv("+count+").txt");
while(file.exists()){
count++;
file = new File("F:\\javaFT\\recv("+count+").txt");
}
//获取输入流,读数据,并把数据保存到文本文件
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
String line;
while ((line = br.readLine()) != null) { //等待读取数据
System.out.println("服务器接收的内容:" + line);
bw.write(line);
bw.newLine();
bw.flush();
}
//给出反馈
BufferedWriter bwFeedback = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bwFeedback.write("文件上传成功!");
bwFeedback.newLine();
bwFeedback.flush();
//释放资源
bw.close();
//s.close();
//ss.close(); //s 由 ss创建,因此可以只写这一句
}catch (IOException e){
e.printStackTrace();
}
}
}
package TCPPackage;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {
public static void main(String[] args) throws IOException {
//创建服务器端的Socket对象(ServerSocket);
//ServerSocket(int port):创建绑定到指定端口的服务器套接字
ServerSocket ss = new ServerSocket(20000);
//为每一个客户端开启一个线程
while(true){
//Socket accept():侦听要连接到此套接字并接收它
Socket s = ss.accept();
Thread t = new Thread(new ServerThread(s));
t.start();
}
}
}