通信
// 服务端import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;public class ServerStringTest {public static void main(String[] args) {ServerSocket ss = null;Socket s = null;BufferedReader br =null;//向客户端发送用PrintStream ps = null;try {//1.创建ServerSocket类型的对象并提供端口号ss = new ServerSocket(8888);// 2.等待客户端连接请求,调用 accept方法System.out.println("请等待客户端的连接请求");s = ss.accept();System.out.println("客户端连接成功");// 3.使用输入输入输出流进行通信// 实现对客户端发来内容的接收并打印br = new BufferedReader(new InputStreamReader(s.getInputStream()));String s1 = br.readLine();System.out.println("客户端发送来的内容为:" + s1);ps = new PrintStream(s.getOutputStream());ps.println("消息收到了");} catch (IOException e) {e.printStackTrace();} finally {// 4.关闭Socket并释放有关资源if(null != br){try {br.close();} catch (IOException e) {e.printStackTrace();}}if(null != s){try {s.close();} catch (IOException e) {e.printStackTrace();}}if(null != ss){try {ss.close();} catch (IOException e) {e.printStackTrace();}}if(null != ps){try {ps.close();} catch (Exception e) {e.printStackTrace();}}}}
}
//客户端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;public class Client {public static void main(String[] args) {Socket s = null;PrintStream ps = null;Scanner sc = null;BufferedReader br =null;try {//1.创建Socket类型的对象,并提供服务器的主机名和端口号s = new Socket("127.0.0.1",8888);System.out.println("连接服务器成功");//2.使用输入输出流进行通信// 实现客户端向服务器发送字符串内容 “hello”ps = new PrintStream(s.getOutputStream());System.out.println("请出入要向服务器发送的内容");sc = new Scanner(System.in);String str1 = sc.next();ps.println(str1);//ps.println("hello");System.out.println("客户端内容发送成功");br = new BufferedReader(new InputStreamReader(s.getInputStream()));String s1 = br.readLine();System.out.println("服务器发送来的内容为:" + s1);} catch (IOException e) {e.printStackTrace();} finally {//3.关闭Socket并释放有关资源if(null != s){try {s.close();} catch (Exception e) {e.printStackTrace();}}if(null != ps){try {ps.close();} catch (Exception e) {e.printStackTrace();}}if(null != br){try {br.close();} catch (IOException e) {e.printStackTrace();}}}}
}