一:
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));
//读取数据: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.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
// 创建套接字Socket 处理异常
Socket s = null;
BufferedWriter writer = null;//BufferedWriter缓冲区输出,用字符流方便些
try {
s = new Socket(“127.0.0.1”,10000);
//获得输出流
OutputStream out = s.getOutputStream();
//OutputStreamWriter 是字符流通向字节流的桥梁
writer = new BufferedWriter(new OutputStreamWriter(out));
//写入数据,writer写入字符流的抽象类;write写入
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();
}
}
}
}
刷新