一:
package cn.tx.demo1.demo2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
ServerSocket ss = null;
Socket s = null;
BufferedReader reader = null;
//创建服务器套接字
try {
ss = new ServerSocket(10000);
System.out.println(“服务器已经启动了…”);
//接收客户端的请求:accept接受
//Socket accept = ss.accept();
s = ss.accept();
//获得流的对象:InputStream输入流
InputStream in = s.getInputStream();
//BufferedReader缓冲区读取 Reader:阅读器,InputStreamReader字符流
reader = new BufferedReader(new InputStreamReader(in));
while (true){
//读取数据:readLine读取一行
String line = reader.readLine();
//获得地址getInetAddress
InetAddress address = s.getInetAddress();
//getHostAddress获得主机地址
String ip = address.getHostAddress();
System.out.println(ip+“发送了:”+line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {//处理异常快捷键ctrl+alt+t
if (reader != null){
reader.close();
}
if (s != null){
s.close();
}
if (ss != null){
ss.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二:
package cn.tx.demo1.demo2;
import java.io.*;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
// 创建套接字Socket 处理异常
Socket s = null;
BufferedWriter writer = null;//BufferedWriter缓冲区输出,用字符流方便些
BufferedReader reader = null;//BufferedReader缓冲区读取
try {
s = new Socket(“127.0.0.1”,10000);
//获得输出流
OutputStream out = s.getOutputStream();
//OutputStreamWriter 是字符流通向字节流的桥梁;输出流
writer = new BufferedWriter(new OutputStreamWriter(out));
//InputStreamReader输入流
reader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while (true){
line = reader.readLine();//readLine逐行读取
//写入数据,writer写入字符流的抽象类;write写入
writer.write(line);// writer.write(“老师好!”);
writer.newLine();//newLine换行
writer.flush();//flush刷新
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (s != null){
s.close();
}
if (writer != null){
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
输入后 记得敲回车,本人老忘。