客户端:
package Dem2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
*/
public class TcpClient {
public static void main(String[] args) throws Exception {
//1。创建一个客户端的对象
InetAddress address = InetAddress.getLocalHost();
Socket s=new Socket(address,12544);
//3.获取输入输出流用于交互
OutputStream outputStream = s.getOutputStream();
InputStream inputStream =s.getInputStream();
//4.封装为高级流,拥有更快的效率
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(outputStream));
Scanner sc=new Scanner(System.in);
System.out.println("请开始你的表演:");
while(true) {
String nextLine = sc.nextLine();
bw.write(nextLine);
bw.newLine();
bw.flush();
System.out.println("服务器:");
String readLine = br.readLine();
System.out.println(readLine);
}
}
}
服务端:
package Dem2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*/
public class TcpServer {
public static void main(String[] args) throws Exception {
//1。创建一个服务器的对象2
ServerSocket s=new ServerSocket(12544);
//2.监听是否有客户端访问
Socket ss = s.accept();
//3.获取输入输出流用于交互
OutputStream outputStream = ss.getOutputStream();
InputStream inputStream = ss.getInputStream();
//4.封装为高级流,拥有更快的效率
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(outputStream));
//5.服务端不能主动访问客户端,所以第一次交互只能响应,接收客户端的请求
Scanner sc=new Scanner(System.in);
while(true) {
System.out.println("客户端:");
String readLine = br.readLine();
System.out.println(readLine);
String nextLine = sc.nextLine();
bw.write(nextLine);
bw.newLine();
bw.flush();
}
}
}