package socket;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
/**
* TCP通信的服务器端
*/
public class TCPServerTest {
public static void main(String[] args) {
ServerSocket ss = null;
PrintWriter pw = null;
BufferedReader br = null;
try {
ss = new ServerSocket(8888); //创建服务器Server并绑定到指定端口
System.out.println("服务器开始监听8888端口....");
Socket so = ss.accept(); //监听并接收客户端的TCP连接,返回与该客户端通信的Socket
System.out.println("服务器接收到了一个客户端:" + so.getRemoteSocketAddress());
//接收
br = new BufferedReader(new InputStreamReader(so.getInputStream()));
String str = br.readLine();
System.out.println("客户端说:" + str);
//从与客户端对应的Socket实例中获取字节输出流并转换成打印字符输出流,带自动刷新功能
// pw = new PrintWriter(new OutputStreamWriter(so.getOutputStream()), true);
// pw.println("你好,客户端!今天是:" + new Date());
DataOutputStream dis = new DataOutputStream(so.getOutputStream());
String result = "你好,客户端!今天是:" + new Date();
dis.write(result.getBytes());
dis.flush();
//PrintStream System.in; 代表标准输入
} catch (IOException e) {
e.printStackTrace();
}finally{
if(null != pw){
pw.close();
}
if(null != br){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != ss){
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* TCP通信的客户端
*/
public class TCPClientTest {
public static void main(String[] args) {
Socket s = null;
BufferedReader br = null;
PrintWriter pw = null;
try {
s = new Socket("127.0.0.1",8888); //创建客户端Socket,并连接到指定IP地址和端口的服务器端程序
//发
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);
pw.println("你好,服务器!");
//收
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println("服务器说:" + str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(null != pw){
pw.close();
}
if(null != br){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != s){
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}