客户端
1、连接服务器Socket
2、发送消息
public class TcpClientDemo1 {
public static void main(String[] args) throws Exception{
//获取服务器的地址,端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
//创建一个socket连接
Socket socket = new Socket(serverIP,port);
//发送消息
OutputStream os = socket.getOutputStream();
os.write("我是你爸爸".getBytes());
os.close();
socket.close();
}
}
服务器
1、建立服务的端口ServerSocket
2、等待用户的链接accept
3、接收用户发送的消息
public class TcpServerDemo1 {
public static void main(String[] args) {
//创建一个地址
ServerSocket serverSocket = null;
ByteArrayOutputStream bos =null;
Socket socket =null;
InputStream is =null;
try {
serverSocket = new ServerSocket(9999);
//循环接收消息
while (true) {
//等待客户端连接
socket = serverSocket.accept();
//读取客户端的消息
is = socket.getInputStream();
//管道流
bos = new ByteArrayOutputStream();
int len;
byte[] buff = new byte[1024];
while ((len = is.read(buff)) != -1) {
bos.write(buff, 0, len);
}
System.out.println(bos.toString());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bos!=null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
TCP实现文件传输功能
public class TcpServerDemo2 {
public static void main(String[] args) throws Exception{
//创建服务
ServerSocket serverSocket = new ServerSocket(9000);
//等待客户端连接
Socket socket = serverSocket.accept();
//获取输入流
InputStream is = socket.getInputStream();
//文件输出
FileOutputStream fis = new FileOutputStream(new File("recev.txt"));
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fis.write(buffer,0,len);
}
//通知客户端已经接收完毕了
OutputStream os = socket.getOutputStream();
os.write("我已经接收完毕了!".getBytes());
//关闭资源
os.close();
fis.close();
is.close();
socket.close();
serverSocket.close();
}
}
public class TcpClientDemo2 {
public static void main(String[] args) throws Exception{
//1、创建socket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
//2、创建一个输出流
OutputStream os = socket.getOutputStream();
//3、读取文件
FileInputStream fis = new FileInputStream(new File("file.txt"));
//4、写出文件
int len;
byte[] buffer = new byte[1024];
while((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
//通知服务器,我已经执行完了
socket.shutdownOutput();//我已经传输完了
//接收服务端发送的接收成功通知
InputStream is = socket.getInputStream();
//创建管道流(中间流)输出结果
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len2;
byte[] buffer2 = new byte[1024];
while((len2=is.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
//关闭
baos.close();
is.close();
fis.close();
os.close();
socket.close();
}
}