javasocket编程(java websocket编程)
大家好,如果您还对javasocket编程不太了解,没有关系,今天就由本站为大家分享javasocket编程的知识,包括java websocket编程的问题都会给大家分析到,还望可以解决大家的问题,下面我们就开始吧!
1本文目录一览
- 1、java socket编程 readline()读取问题,为啥在client端刚连接上就开始无限循环,停不下来?
- 2、java socket网络编程
- 3、java Socket网络编程
- 4、Java的Socket编程?
- 5、在javasocket网络编程中,开发基于udp协议的程序使用的套接字有哪些
- 6、java socket 编程 登录
2java socket编程 readline()读取问题,为啥在client端刚连接上就开始无限循环,停不下来?
改一下
scan.nextLine();//阻塞,排除是socket建立太慢导致的
String str=null;
这两行删除,没用
str=br.readLine();
这个改成
br=scan.readLine();
然后你再试一下
顺便再说一下,这个程序我写过,我开始想的也是客户端发送的数据服务器端可以实时接收,但是我发现我错了,因为Scanner 的阻塞,如果客户端发送消息服务器端必须也得发送一个消息才能收到,这个内容可以是任意内容,比如一个回车,如果想让客户端 或服务器端可以实时接收到消息,在控制台中是不可能实现的,除非使用swing框架,一个文本框负负责发送,一个文本框负责接收,不过听他们说swing现在企业中根本不用了,所有我也就没有深入研究,劝你也放弃吧,研究这个没什么用,除非你能在网页上实现,或者做一个程序,至于我写的源码,如果你要我可以发给你
对了再说下你这个问题出现的原因
你这个是因为循环中没有阻塞语句,而且br没有接收到值,所有它会一直打印null
3java socket网络编程
//==============Server.java=================//
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(12345);
System.out.println("服务器就绪,请启动客户端.");
Socket so = s.accept();
byte[] buff = new byte[1024];
int read = so.getInputStream().read(buff);
String[] abc=new String(buff,0,read).split("\\D+");
int a = Integer.parseInt(abc[0]);
int b = Integer.parseInt(abc[1]);
int c = Integer.parseInt(abc[2]);
if(!cbt(a,b,c))
so.getOutputStream().write("输入的数据无法组成三角形.".getBytes());
else
so.getOutputStream().write(getArea(a,b,c).getBytes());
so.getOutputStream().flush();
so.close();
s.close();
}
private static String getArea(int a, int b, int c) {
float s = (a+b+c)/2f;
return "面积: "+Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
private static boolean cbt(int a, int b, int c) {
return a0b0c0a+bcb+caa+cb;
}
}
//=================Client.java======================//
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("输入三角形的三边并用逗号隔开,如: (3,4,5) ");
byte[] buff=new byte[64];
int r = System.in.read(buff);
String ipaddr = "localhost";//根据情况改变,在本机调试就不改了
Socket so = new Socket(ipaddr,12345);
so.getOutputStream().write(new String(buff,0,r).getBytes());
r = so.getInputStream().read(buff);
so.close();
String rs = new String(buff,0,r);
System.out.println(rs);
}
}
//先启动Server,再启动Client
4java Socket网络编程
//向输出流中写入数据
out.write("你好,服务端".getBytes());
out.write("我是客户端".getBytes());
out.flush();
5Java的Socket编程?
要通信首先要建立socket链接。
1 ab客户端与服务端建立socket链接
2 a客户端发送消息到服务端
3 服务端收到消息后,发送到指定的b客户端
4 b客户端处理来自服务端的消息
6在javasocket网络编程中,开发基于udp协议的程序使用的套接字有哪些
Socket套接字,是由系统提供用于网络通信的技术(操作系统给应用程序提供的一组API叫做Socket API),是基于TCP/IP协议的网络通信的基本操作单元。基于Socket套接字的网络程序开发就是网络编程。
socket可以视为是应用层和传输层之间的通信桥梁;
传输层的核心协议有两种:TCP,UDP;socket API也有对应的两组,由于TCP和UDP协议差别很大,因此,这两组API差别也挺大。
分类:
Socket套接字主要针对传输层协议划分为如下三类:
流套接字:使用传输层TCP协议
TCP,即Transmission Control Protocol(传输控制协议),传输层协议;
TCP的特点:
有连接:像打电话,得先接通,才能交互数据;
可靠传输:传输过程中,发送方知道接收方有没有收到数据.(打电话就是可靠传输);
面向字节流:以字节为单位进行传输.(非常类似于文件操作中的字节流);
全双工:一条链路,双向通信;
有接收缓冲区,也有发送缓冲区。
大小不限
对于字节流来说,可以简单的理解为,传输数据是基于IO流,流式数据的特征就是在IO流没有关闭的情况下,是无边界的数据,可以多次发送,也可以分开多次接收。
数据报套接字:使用传输层UDP协议
UDP,即User Datagram Protocol(用户数据报协议),传输层协议。
UDP的特点:
无连接:像发微信,不需要接通,直接就能发数据;
不可靠传输:传输过程中,发送方不知道接收方有没有收到数据.(发微信就是不可靠传输);
面向数据报:以数据报为单位进行传输(一个数据报都会明确大小)一次发送/接收必须是一个完整的数据报,不能是半个,也不能是一个半;
全双工:一条链路,双向通信;
有接收缓冲区,无发送缓冲区;
大小受限:一次最多传输64k;
对于数据报来说,可以简单的理解为,传输数据是一块一块的,发送一块数据假如100个字节,必须一次发送,接收也必须一次接收100个字节,而不能分100次,每次接收1个字节。
原始套接字
原始套接字用于自定义传输层协议,用于读写内核没有处理的IP协议数据。
二、UDP数据报套接字编程
UDPSocket中,主要涉及到两类:DatagramSocket、DatagramPacket;
DatagramSocket API
DatagramSocket 创建了一个UDP版本的Socket对象,用于发送和接收UDP数据报,代表着操作系统中的一个socket文件,(操作系统实现的功能–)代表着网卡硬件设备的抽象体现。
DatagramSocket 构造方法:
方法签名 方法说明
DatagramSocket() 创建一个UDP数据报套接字的Socket,绑定到本机任意一个随机端口(一般用于客户端)
DatagramSocket(int port) 创建一个UDP数据报套接字的Socket,绑定到本机指定的端口(一般用于服务端)
DatagramSocket 方法:
方法签名 方法说明
void receive(DatagramPacket p) 从此套接字接收数据报(如果没有接收到数据报,该方法会阻塞等待)
void send(DatagramPacket p) 从此套接字发送数据报包(不会阻塞等待,直接发送)
void close() 关闭此数据报套接字
DatagramPacket API
代表了一个UDP数据报,是UDP Socket发送和接收的数据报,每次发送/接收数据报,都是在传输一个DatagramPacket对象。
DatagramPacket 构造方法:
方法签名 方法说明
DatagramPacket(byte[] buf, int length) 构造一个DatagramPacket以用来接收数据报,接收的数据保存在字节数组(第一个参数buf)中,接收指定长度(第二个参数length)
DatagramPacket(byte[] buf, int offset, int length,SocketAddress address) 构造一个DatagramPacket以用来发送数据报,发送的数据为字节数组(第一个参数buf)中,从0到指定长度(第二个参数length)。address指定目的主机的IP和端口号
DatagramPacket 方法:
方法签名 方法说明
InetAddress getAddress() 从接收的数据报中,获取发送端主机IP地址;或从发送的数据报中,获取接收端主机IP地址
int getPort() 从接收的数据报中,获取发送端主机的端口号;或从发送的数据报中,获取接收端主机端口号
byte[] getData() 获取数据报中的数据
构造UDP发送的数据报时,需要传入 SocketAddress ,该对象可以使用 InetSocketAddress 来创建。
InetSocketAddress API
InetSocketAddress ( SocketAddress 的子类 )构造方法:
方法签名 方法说明
InetSocketAddress(InetAddress addr, int port) 创建一个Socket地址,包含IP地址和端口号
示例1:写一个简单的客户端服务程序,回显服务(EchoSever)
在这里插入图片描述
构建Socket对象有很多失败的可能:
端口号已经被占用,同一个主机的两个程序不能有相同的端口号(这就好比两个人不能拥有相同的电话号码);
此处,多个进程不能绑定同一个端口号,但是一个进程可以绑定多个端口,(这就好比一个人可以拥有多个手机号),一个进程可以创建多个Socket对象,每个Socket都绑定自己的端口。
每个进程能够打开的文件个数是有上限的,如果进程之间已经打开了很多文件,就可能导致此时的Socket文件不能顺利打开;
在这里插入图片描述
这个长度不一定是1024,假设这里的UDP数据最长是1024,实际的数据可能不够1024.
在这里插入图片描述
这里的参数不再是一个空的字节数组了,response是刚才根据请求计算的得到的响应,是非空的,DatagramPacket 里面的数据就是String response的数据。
response.getBytes().length:这里拿到的是字节数组的长度(字节的个数),而response.length得到的是字符的长度。
五元组
一次通信是由5个核心信息描述的:源IP、 源端口、 目的IP、 目的端口、 协议类型。
站在客户端角度:
源IP:本机IP;
源端口:系统分配的端口;
目的IP:服务器的IP;
目的端口:服务器的端口;
协议类型:TCP;
站在服务器的角度:
源IP:服务器程序本机的IP;
源端口:服务器绑定的端口(此处手动指定了9090);
目的IP:包含在收到的数据报中(客户端的IP);
目的端口:包含在收到的数据报中(客户端的端口);
协议类型:UDP;
7java socket 编程 登录
给你一个聊天室的,这个是客户端之间的通信,服务器负责接收和转发,你所要的服务器与客户端对发,只要给服务器写个界面显示和输入就行,所有代码如下:
你测试的时候应该把所有代码放在同一个工程下,因为客户端可服务器共用同一个POJO,里面有些包的错误,删除掉就行了
服务器代码,即服务器入口程序:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashSet;
public class ChatRoomServer {
private ServerSocket ss;
private HashSetSocket allSockets;
private UserDao dao;
public ChatRoomServer(){
try {
ss=new ServerSocket(9999);
allSockets=new HashSetSocket();
dao=new UserDaoForTextFile(new File("d:/stu/user.txt"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void startService() throws IOException{
while(true){
Socket s=ss.accept();
allSockets.add(s);
new ChatRoomServerThread(s).start();
}
}
class ChatRoomServerThread extends Thread{
private Socket s;
public ChatRoomServerThread(Socket s){
this.s=s;
}
public void run(){
//1,得到Socket的输入流,并包装。
//2,循环从输入流中读取一行数据。
//3,每读到一行数据,判断该行是否是退出命令?
//4,如果是退出命令,则将当前socket从集合中删除,关闭当前socket,并跳出循环
//5,如果不是退出命令,则将该消model.getCurrentUser().getName()息转发给所有在线的客户端。
// 循环遍历allSockets集合,得到每一个socket的输出流,向流中写出该消息。
BufferedReader br=null;
String str = null;
try {
br = new BufferedReader(new InputStreamReader(s
.getInputStream()));
while((str=br.readLine())!=null ){
if(str.indexOf("%EXIT%")==0){
allSockets.remove(s);
//向其他客户端发送XXX退出的消息
sendMessageToAllClient(str.split(":")[1]+"离开聊天室!");
s.close();
break;
}else if(str.indexOf("%LOGIN%")==0){
String userName=str.split(":")[1];
String password=str.split(":")[2];
User user=dao.getUser(userName, password);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
oos.writeObject(user);
oos.flush();
if(user!=null){
sendMessageToAllClient(user.getName()+"进入聊天室!");
}
str = null;
}
if(str!=null){
sendMessageToAllClient(str);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessageToAllClient(String message)throws IOException{
Date date=new Date();
System.out.println(s.getInetAddress()+":"+message+"\t["+date+"]");
for(Socket temps:allSockets){
PrintWriter pw=new PrintWriter(temps.getOutputStream());
pw.println(message+"\t["+date+"]");
pw.flush();
}
}
}
public static void main(String[] args) {
try {
new ChatRoomServer().startService();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端代码:
总共4个:
1:入口程序:
public class ChatRoomClient {
private ClientModel model;
public ChatRoomClient(){
// String hostName = JOptionPane.showInputDialog(null,
// "请输入服务器主机名:");
// String portName = JOptionPane
// .showInputDialog(null, "请输入端口号:");
//固定服务端IP和端口
model=new ClientModel("127.0.0.1",Integer.parseInt("9999"));
model.createSocket();
new LoginFrame(model).showMe();
}
public static void main(String[] args) {
new ChatRoomClient();
}
}
2:登陆后显示界面:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ClientMainFrame extends JFrame{
private JTextArea area;
private JTextField field;
private JLabel label;
private JButton button;
private ClientModel model;
public ClientMainFrame(){
super("聊天室客户端v1.0");
area=new JTextArea(20,40);
field=new JTextField(25);
button=new JButton("发送");
label=new JLabel();
JScrollPane jsp=new JScrollPane(area);
this.add(jsp,BorderLayout.CENTER);
JPanel panel=new JPanel();
panel.add(label);
panel.add(field);
panel.add(button);
this.add(panel,BorderLayout.SOUTH);
addEventHandler();
}
public ClientMainFrame(ClientModel model){
this();
this.model=model;
label.setText(model.getCurrentUser().getName());
}
public void addEventHandler(){
ActionListener lis=new SendEventListener();
button.addActionListener(lis);
field.addActionListener(lis);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0) {
int op=JOptionPane.showConfirmDialog(null,"确认退出聊天室吗?","确认退出",JOptionPane.YES_NO_OPTION);
if(op==JOptionPane.YES_OPTION){
PrintWriter pw = model.getOutputStream();
if(model.getCurrentUser().getName()!=null){
pw.println("%EXIT%:"+model.getCurrentUser().getName());
pw.flush();
}
try {
Thread.sleep(200);
} catch (Exception e) {
}
System.exit(0);
}
}
});
}
public void showMe(){
this.pack();
this.setVisible(true);
this.setLocation(300,300);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
new ReadMessageThread().start();
}
class SendEventListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str=field.getText().trim();
if(str.equals("")){
JOptionPane.showMessageDialog(null, "不能发送空消息!");
return;
}
PrintWriter pw = model.getOutputStream();
pw.println(model.getCurrentUser().getName()+":"+str);
pw.flush();
field.setText("");
}
}
class ReadMessageThread extends Thread{
public void run(){
while(true){
try {
BufferedReader br = model.getInputStream();
String str=br.readLine();
area.append(str+"\n");
} catch (IOException e) {
}
}
}
}
}
3:登陆界面:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JLabel lab1 = null;
private JLabel lab2 = null;
private JLabel lab3 = null;
private JTextField userNameField = null;
private JPasswordField passwordField = null;
private JButton loginButton = null;
private JButton registerButton = null;
private JButton cancelButton = null;
private ClientModel model = null;
/**
* This method initializes userNameField
*
* @return javax.swing.JTextField
*/
private JTextField getUserNameField() {
if (userNameField == null) {
userNameField = new JTextField();
userNameField.setSize(new Dimension(171, 33));
userNameField.setFont(new Font("Dialog", Font.PLAIN, 18));
userNameField.setLocation(new Point(140, 70));
}
return userNameField;
}
/**
* This method initializes passwordField
*
* @return javax.swing.JPasswordField
*/
private JPasswordField getPasswordField() {
if (passwordField == null) {
passwordField = new JPasswordField();
passwordField.setSize(new Dimension(173, 30));
passwordField.setFont(new Font("Dialog", Font.PLAIN, 18));
passwordField.setLocation(new Point(140, 110));
}
return passwordField;
}
/**
* This method initializes loginButton
*
* @return javax.swing.JButton
*/
private JButton getLoginButton() {
if (loginButton == null) {
loginButton = new JButton();
loginButton.setLocation(new Point(25, 180));
loginButton.setText("登录");
loginButton.setSize(new Dimension(75, 30));
}
return loginButton;
}
/**
* This method initializes cancelButton
*
* @return javax.swing.JButton
*/
private JButton getCancelButton() {
if (cancelButton == null) {
cancelButton = new JButton();
cancelButton.setLocation(new Point(270, 180));
cancelButton.setText("取消");
cancelButton.setSize(new Dimension(75, 30));
}
return cancelButton;
}
/**
* 显示界面的方法,在该方法中调用addEventHandler()方法给组件添加事件监听器
*
*/
public void showMe(){
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
this.setLocation(300,200);
addEventHandler();
}
/**
* 该方法用于给组件添加事件监听
*
*/
public void addEventHandler(){
ActionListener loginListener=new LoginEventListener();
loginButton.addActionListener(loginListener);
passwordField.addActionListener(loginListener);
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
model.getSocket().close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0) {
try {
model.getSocket().close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
}
/**
* 该内部类用来监听登录事件
* @author Administrator
*
*/
class LoginEventListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
//?????登录的代码
//1,判断用户名和密码是否为空
//2,从clientmodel得到输出流,PrintWriter
//3,发送登录请求给服务器
//pw.println("%LOGIN%:userName:password");
//4,从socket得到对象输入流,从流中读取一个对象。
//5,如果读到的对象为null,则显示登录失败的消息。
//6,如果读到的对象不为空,则转成User对象,并且将
// clientModel的currentUser对象设置为该对象。
//7,并销毁当前窗口,打开主界面窗口。
String userName = userNameField.getText();
char[] c = passwordField.getPassword();
String password = String.valueOf(c);
if(userName == null || userName.equals("")){
JOptionPane.showMessageDialog(null,"用户名不能为空");
return;
}
if(password == null || password.equals("")){
JOptionPane.showMessageDialog(null,"密码名不能为空");
return;
}
PrintWriter pw = model.getOutputStream();
pw.println("%LOGIN%:"+userName+":"+password);
pw.flush();
try {
InputStream is = model.getSocket().getInputStream();
System.out.println("is"+is.getClass());
ObjectInputStream ois = new ObjectInputStream(is);
Object obj = ois.readObject();
if(obj != null){
User user = (User)obj;
if(user != null){
model.setCurrentUser(user);
LoginFrame.this.dispose();
new ClientMainFrame(model).showMe();
}
}
else{
JOptionPane.showMessageDialog(null,"用户名或密码错误,请重新输入");
userNameField.setText("");
passwordField.setText("");
return;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
new LoginFrame().showMe();
}
/**
* This is the default constructor
*/
public LoginFrame(ClientModel model) {
this();
this.model=model;
}
public LoginFrame(){
super();
initialize();
}
public ClientModel getModel() {
return model;
}
public void setModel(ClientModel model) {
this.model = model;
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(362, 267);
this.setContentPane(getJContentPane());
this.setTitle("达内聊天室--用户登录");
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
lab3 = new JLabel();
lab3.setText("密 码:");
lab3.setSize(new Dimension(80, 30));
lab3.setFont(new Font("Dialog", Font.BOLD, 18));
lab3.setLocation(new Point(50, 110));
lab2 = new JLabel();
lab2.setText("用户名:");
lab2.setSize(new Dimension(80, 30));
lab2.setToolTipText("");
lab2.setFont(new Font("Dialog", Font.BOLD, 18));
lab2.setLocation(new Point(50, 70));
lab1 = new JLabel();
lab1.setBounds(new Rectangle(54, 12, 245, 43));
lab1.setFont(new Font("Dialog", Font.BOLD, 24));
lab1.setForeground(new Color(0, 0, 204));
lab1.setText("聊天室--用户登录");
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(lab1, null);
jContentPane.add(lab2, null);
jContentPane.add(lab3, null);
jContentPane.add(getUserNameField(), null);
jContentPane.add(getPasswordField(), null);
jContentPane.add(getLoginButton(), null);
jContentPane.add(getCancelButton(), null);
}
return jContentPane;
}
}
4:客户端管理socket类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* 该类定义客户端的全局参数,如:Socket,当前用户,流对象等
*
*/
public class ClientModel {
private Socket socket;
private User currentUser;
private BufferedReader br;
private PrintWriter pw;
private String hostName;
private int port;
public Socket getSocket() {
return socket;
}
public ClientModel(String hostName, int port) {
super();
this.hostName = hostName;
this.port = port;
}
public User getCurrentUser() {
return currentUser;
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}
public synchronized Socket createSocket(){
if(socket==null){
try {
socket=new Socket(hostName,port);
}catch (IOException e) {
e.printStackTrace();
return null;
}
}
return socket;
}
public synchronized BufferedReader getInputStream(){
if (br==null) {
try {
br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return br;
}
public synchronized PrintWriter getOutputStream(){
if (pw==null) {
try {
pw = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return pw;
}
public synchronized void closeSocket(){
if(socket!=null){
try {
br.close();
pw.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
socket=null;
br=null;
pw=null;
}
}
这里是工具和POJO类:
User类:
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1986L;
private int id;
private String name;
private String password;
private String email;
public User(){}
public User( String name, String password, String email) {
super();
this.name = name;
this.password = password;
this.email = email;
}
public User( String name, String password) {
super();
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString(){
return id+":"+name+":"+password+":"+email;
}
}
DAO,用于从本地读取配置文件
接口:
public interface UserDao {
public boolean addUser(User user);
public User getUser(String userName,String password);
}
实现类:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class UserDaoForTextFile implements UserDao{
private File userFile;
public UserDaoForTextFile(){
}
public UserDaoForTextFile(File file){
this.userFile = file;
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public synchronized boolean addUser(User user) {
FileInputStream fis = null;
BufferedReader br = null;
int lastId = 0;
try{
fis = new FileInputStream(userFile);
br = new BufferedReader(new InputStreamReader(fis));
String str = null;
String lastLine = null;
while((str=br.readLine()) != null){
//得到最后一行值
lastLine = str;
if(str.split(":")[1].equals(user.getName())){
return false;
}
}
if(lastLine != null)
lastId = Integer.parseInt(lastLine.split(":")[0]);
}catch(Exception e){
e.printStackTrace();
}finally{
if(br!=null)try{br.close();}catch(IOException e){}
if(fis!=null)try{fis.close();}catch(IOException e){}
}
FileOutputStream fos = null;
PrintWriter pw = null;
try{
fos = new FileOutputStream(userFile,true);
pw = new PrintWriter(fos);
user.setId(lastId+1);
pw.println(user);
pw.flush();
return true;
}catch(Exception e){
e.printStackTrace();
}finally{
if(pw!=null)try{pw.close();}catch(Exception e){}
if(fos!=null)try{fos.close();}catch(IOException e){}
}
return false;
}
public synchronized User getUser(String userName, String password) {
FileInputStream fis = null;
BufferedReader br = null;
String str = null;
User user = null;
try{
fis = new FileInputStream(userFile);
br = new BufferedReader(new InputStreamReader(fis));
while((str = br.readLine()) != null){
String[] s = str.split(":");
if(userName.equals(s[1]) password.equals(s[2])){
user = new User();
user.setId(Integer.parseInt(s[0]));
user.setName(s[1]);
user.setPassword(s[2]);
user.setEmail(s[3]);
}
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br!=null)try{br.close();}catch(IOException e){}
if(fis!=null)try{fis.close();}catch(IOException e){}
}
return user;
}
}
配置文件格式为:
id流水号:用户名:密码:邮箱
1:yawin:034437:yawin@126.com
2:zhoujg:034437:zhou@126.com
文章到此结束,如果本次分享的javasocket编程和java websocket编程的问题解决了您的问题,那么我们由衷的感到高兴!