/*
* 基于TCP协议的socket通信,实现用户登录
*/
public class ServerMain1 {
public static void main(String[] args) {
try {
//1.创建一个服务器端的Socket,ServerSocket ,指定绑定的端口,并监听此端口
ServerSocket serverSocket=new ServerSocket(8888);//端口已设置1023以后的端口
//2.调用accept()方法开始监听,等待客户端连接
System.out.println("*****服务器即将启动,等待客户端的连接*******");
Socket socket=serverSocket.accept();
//3.获取输入流,并读取客户端信息
InputStream is=socket.getInputStream();
//4.将字节流包装为字符流
InputStreamReader isr=new InputStreamReader(is);
//5.为字符流添加缓冲区
BufferedReader br=new BufferedReader(isr);
String info=null;
while((info=br.readLine())!=null)
{
System.out.println("我是服务器,客户端说"+info);
}
socket.shutdownInput();//关闭读取流
OutputStream os=socket.getOutputStream();
PrintWriter pw=new PrintWriter(os);
pw.write("欢迎你的登陆!!!");
pw.flush();//刷新缓存
pw.close();
os.close();
br.close();
isr.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
-----------------------
public class ClientMain1 {
public static void main(String[] args) {
try {
//1.创建客户端socket,指定服务器端地址和端口
Socket socket=new Socket("localhost",8888);
//2.获取一个输出流(写入),向服务器端发送信息
OutputStream os=socket.getOutputStream();// 字符输出流
PrintWriter pw=new PrintWriter(os);//将输入流包装为打印流
pw.write("用户名:admin;密码:132");
pw.flush();
socket.shutdownOutput();
InputStream is=socket.getInputStream();
//4.将字节流包装为字符流
InputStreamReader isr=new InputStreamReader(is);
//5.为字符流添加缓冲区
BufferedReader br=new BufferedReader(isr);
String info=null;
while((info=br.readLine())!=null)
{
System.out.println("我是客户端,服务说:"+info);
}
//关闭资源
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注:(运行实例时,请先运行ServerMain1然后在运行ClientMain1,简单的实现服务端接受客户端发送的数据并相应客户端。运行环境jdk1.6)
原文地址:http://kefly.blog.51cto.com/1109349/1584420