简单互动:
服务器:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
BufferedReader bufferedReader = null;
try {
//创建服务器套接字,并指明监听接口
serverSocket = new ServerSocket(6688);
System.out.println("服务器启动!!!");
//.accept(字面意思为接收):接收一个套接字中已建立的连接
Socket socket = serverSocket.accept();
//.getHostAddress()(字面意思即为获取主机地址)
System.out.println("有客户端请求连接,ip:"+ socket.getInetAddress().getHostAddress());
//BufferedReader:(缓冲读写对象)从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
//InputStreamReader(输入流读写对象)getInputStream(获取输入流)
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//readLine:读取流读数据
System.out.println("输出客户端信息:" + bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TCPClient {
public static void main(String[] args) {
Socket socket = null;
BufferedWriter bufferedWriter = null;
//根据ip地址和端口号进行连接
try {
socket = new Socket("127.0.0.1", 6688);
System.out.println("与服务器端建立连接...");
System.out.println("客户端输入信息:");
Scanner sc = new Scanner(System.in);
//bufferedWriter:缓冲输出流
bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//把输入字符串注入缓冲输出流(bufferedWriter)
bufferedWriter.write(sc.nextLine());
bufferedWriter.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}