客户端:
1. import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.*; import java.util.Scanner; public class TCPseed { public static void main(String[] args) { //创建Socket服务 字符输出流 读取流 Socket s = null; PrintWriter out = null; BufferedReader bufIn = null; try { //指定IP地址和端口 s = new Socket("这里填服务端IP地址", 10020); //指定输出流为s的网络输出流,并可以自动刷新 out = new PrintWriter(s.getOutputStream(),true); //输入流为s的网络输入流 bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } Scanner input = new Scanner(System.in); String line = null; while(!("over".equals(line))) { line = input.nextLine(); out.println(line); String str = null; try { str = bufIn.readLine(); } catch (Exception e) { // TODO: handle exception } System.out.println(str); } try { bufIn.close(); s.close(); out.close(); } catch (Exception e) { // TODO: handle exception } } }
服务端:
import java.io.*; import java.net.*; public class TCPrece { //这里直接把异常抛出了 public static void main(String[] args) throws Exception{ //创建服务端对象,监听10020端口 ServerSocket ss = new ServerSocket(10020); //用ServerSocket里面的accept方法获取客户端对象 Socket s = ss.accept(); //获取对方IP 并输出 System.out.println(s.getInetAddress().getHostAddress()+"连接"); BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(),true); String str = null; while((str=bufIn.readLine())!=null) { System.out.println(str); //变成大写并返回 out.println(str.toUpperCase()); } ss.close(); s.close(); bufIn.close(); out.close(); } }