客户端:
package TCP;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 客户端
* @author 14431
*
*/
public class Client {
public static void main(String[] args) {
try {
//1.创建客户端socket,指定服务器地址和端口
Socket socket =new Socket(InetAddress.getLocalHost(),6666);
//2.获取输出流,向服务器发送信息
OutputStream os= socket.getOutputStream();//字节输出流
PrintWriter pw =new PrintWriter(os);//将输出流包装为打印流
pw.write("用户名:admin;密码:123");//发送信息
pw.flush();//刷新缓存,输出信息
socket.shutdownInput();//关闭输出流
//3.关闭资源
os.close();
pw.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器:
package TCP;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 基于TCP协议的Socket通信,实现用户登录
* @author 14431
*服务器端
*/
public class Server {
public static void main(String[] args) {
try {
//1.创建一个服务器的Socket,即ServerSocket,
//指定绑定端口,并监听端口
ServerSocket serverSocket =new ServerSocket(6666);
//2.调用accept()方法进行监听,等待客户端连接
System.out.println("服务器启动中......");
Socket socket =serverSocket.accept(); //若客户端连接上,则会返回一个实例
//3.获取输入流,并读取客户端信息
InputStream is = socket.getInputStream(); //字节输入流
InputStreamReader isr =new InputStreamReader(is); //转换为字符输入流
BufferedReader br =new BufferedReader(isr);
String info =br.readLine();
while((info=br.readLine())!=null) {
System.out.println("客户端说:"+info);
info=br.readLine();
}
socket.shutdownInput();//关闭输入流
//4.关闭资源
br.close();
is.close();
isr.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}