JAVA Socket编程
多人聊天室
客户端源代码
import java.awt.BorderLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.JTextField; /*客户端窗口构建*/ public class ClientChatView extends JFrame{ //显示文本的窗口 private JTextArea ta = new JTextArea(10,20); //输入文本的窗口 private JTextField tf = new JTextField(20); //创建客户端socket private Socket cs = null; //指定客户端socket端口 private static final int PORT = 8888; //指定客户端socket的ip地址 private static final String CONNSTR = "127.0.0.1"; //网络输出流 private DataOutputStream dos = null; private boolean isconn = false; //ClientChatView构造方法 public ClientChatView() throws HeadlessException { super(); } //ClientChatView初始化方法 public void init() { //设置窗口标题 this.setTitle("ClientView"); //设置窗口样式 this.add(ta,BorderLayout.CENTER); this.add(tf,BorderLayout.SOUTH); //设置窗口总大小 this.setBounds(300, 300, 300, 400); //关闭上边窗口输入功能 ta.setEditable(false); //光标聚焦 tf.requestFocus(); //点击窗口叉号=关闭客户端 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //监听tf输入到ta,并清除掉tf中内容 tf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //获取tf中输入的信息 String strSend = tf.getText(); //使用send方法发送信息给服务器端 send(strSend); if (strSend.trim().length()==0) { return;//tf中没有输入 } tf.setText(""); //加入到ta中 //ta.append(strSend+"n"); } }); //正式创建客户端Socket /*try catch处理异常*/ try { cs = new Socket(CONNSTR,PORT); isconn = true; } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } this.setVisible(true); new Thread(new Receive()).start(); } //发送信息到服务器上的方法 public void send(String str) { try { //使用socket的getinputstream方法获取网络字节输入流对象 dos = new DataOutputStream(cs.getOutputStream()); //将输出流信息发送给服务器 dos.writeUTF(str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //多线程的类,实现多线程接收 class Receive implements Runnable{ public void run() { try { while(isconn) { DataInputStream dis = new DataInputStream(cs.getInputStream()); String str = dis.readUTF(); ta.append(str); } }catch (SocketException e3) { System.out.println("Sever stopped"); ta.append("Server stopped"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { ClientChatView cc = new ClientChatView(); cc.init(); } }
服务器端源代码
import java.awt.BorderLayout; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.Iterator; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.JPanel; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.ActionEvent; //服务器窗口创建 /*一个框框,两个按钮*/ public class ServerChat extends JFrame{ //设置服务器窗口——一个框框 JTextArea serverTa = new JTextArea(); //创建服务器窗口——两个按钮 private JPanel btnTool = new JPanel(); private JButton starBtn = new JButton("start"); private JButton stopBtn = new JButton("stop"); //设置服务器端socket的端口号 private static final int PORT = 8888; //创建服务器端socket private ServerSocket ss = null; private Socket s = null; //设置服务器启动的标志 private boolean isStart = false; //设置连接到服务器上的客户socket数组 private ArrayList<ClientConn> cclist=new ArrayList<ClientConn>(); //初始化服务器窗口 public void init() { //设置窗口标题 this.setTitle("ServerView"); //设置窗口样式 this.add(serverTa,BorderLayout.CENTER); btnTool.add(starBtn); btnTool.add(stopBtn); this.add(btnTool,BorderLayout.SOUTH); //设置窗口总大小 this.setBounds(0, 0, 500, 500); //设置serverTa不可输入 serverTa.setEditable(false); //点击叉号关闭窗口,同时停止服务器运行,后面改进 //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //判断服务器是否启动 if(isStart) { serverTa.append("Server started.\n"); }else { serverTa.append("Server not start."+"n"); } //监听开始按钮,启动服务器 starBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if(ss==null) { ss=new ServerSocket(PORT); } isStart = true; serverTa.append("Server started."+"n"); }catch(IOException e1) { e1.printStackTrace(); } } }); //监听停止按钮,关闭服务器 stopBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //关机 isStart = false; try { if(s!=null) { s.close(); } if(ss!=null) { ss.close(); } serverTa.append("Server stopped"); System.exit(0); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); //监听窗口(叉号) this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //关机 isStart = false; try { if(s!=null) { s.close(); } if(ss!=null) { ss.close(); } serverTa.append("Server stopped"); System.exit(0); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); this.setVisible(true); startServer(); } /*服务器启动方法*/ public void startServer() { //正式创建服务器socket try { try { ss = new ServerSocket(PORT); isStart = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //只要服务器运行就一直等待客户连接,接受多个客户端连接 while (isStart) { //获取客户端socket对象 s = ss.accept(); //将该对象添加进数组 cclist.add(new ClientConn(s)); //在控制台显示相关信息 System.out.println("A Client connected" + s.getInetAddress() + "/" + s.getPort()+"n"); //在服务器窗口显示相关信息 serverTa.append("A Client connected" + s.getInetAddress() + "/" + s.getPort()+"n"); } }catch (SocketException e3) { System.out.println("Sever stopped"); serverTa.append("Server stopped"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /*服务器停止方法*/ public void stopServer() { } /* 服务器接收数据方法,应该是多线程的接收*/ // public void reciveStr() { // try { // dis = new DataInputStream(s.getInputStream()); // String str = dis.readUTF(); // System.out.println(str); // serverTa.append(str); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // } /*该对象是所有连接到服务器端的连接对象*/ class ClientConn implements Runnable{ Socket s= null; public ClientConn(Socket s) { this.s= s; //得到一个s就创建一个线程,并运行下面的try/catch (new Thread(this)).start(); } //同时接受客户端信息-多线程的接收 public void run() { try { //使用getinputstream获取网络输入流(客户端输入流) DataInputStream dis = new DataInputStream(s.getInputStream()); while (isStart) { //读取输入流中信息 String str = dis.readUTF(); //在控制台和服务器窗口打印 System.out.println(s.getInetAddress()+"|"+s.getPort()+"说:"+str + "n"); serverTa.append(s.getInetAddress()+"|"+s.getPort()+"说:"+str + "n"); String strsend = s.getInetAddress()+"|"+s.getPort()+"说:"+str + "n"; //遍历后再发送 Iterator<ClientConn> it=cclist.iterator(); while(it.hasNext()) { ClientConn o=it.next(); o.resend(strsend); } } }catch(SocketException e) { System.out.println("A Client leave"); serverTa.append("a Client leave:"+s.getInetAddress()+"|"+s.getPort()+"n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //服务器分发数据,通过遍历,发生给每个客户端,在客户端同样要多线程的接收 public void resend(String str) { try { DataOutputStream dos = new DataOutputStream(this.s.getOutputStream()); dos.writeUTF(str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { ServerChat sc = new ServerChat(); sc.init(); } }
运行展示
邮件发送客户端
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.JTextField; import com.sun.jdi.connect.Transport; public class EmailClient extends JFrame{ //设置窗口 //设置邮件主题窗口 private JTextField Title = new JTextField("Title:",20); //邮件发送目的的窗口 private JTextField TO = new JTextField("TO:",20); //文本窗口 private JTextArea ta = new JTextArea(10,20); private JButton sendBtn = new JButton("send"); public void init() { //设置窗口标题 this.setTitle("ClientView"); //设置窗口样式a this.add(ta,BorderLayout.CENTER); this.add(Title,BorderLayout.NORTH); this.add(TO,BorderLayout.SOUTH); this.add(sendBtn, BorderLayout.EAST); //设置窗口总大小 this.setBounds(300, 300, 300, 400); //光标聚焦 TO.requestFocus(); //点击窗口叉号=关闭客户端 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置监听,判断是否开始发送 sendBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { mail(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); this.setVisible(true); } public void mail () throws Exception { // 用于连接邮件服务器的参数配置 Properties props = new Properties(); props.setProperty("mail.host", "smtp.qq.com"); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.auth", "true"); // 根据参数配置,创建会话对象 Session session= Session.getInstance(props); session.setDebug(true); // 创建邮件内容对象 MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("3271656206@qq.com", "Kechen", "UTF-8")); // 收件人 message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(TO.getText().substring(3), "you", "UTF-8")); // To: 增加收件人(可选) //message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("dd@receive.com", "USER_DD", "UTF-8")); // Cc: 抄送(可选) //message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("ee@receive.com", "USER_EE", "UTF-8")); // Bcc: 密送(可选) //message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("ff@receive.com", "USER_FF", "UTF-8")); //邮件主题 message.setSubject(Title.getText().substring(6), "UTF-8"); //邮件正文 message.setContent(ta.getText(), "text/html;charset=UTF-8"); //定义传输协议 javax.mail.Transport transport = session.getTransport("smtp"); transport.connect("smtp.qq.com","3271656206@qq.com","dnrfvjtohotkchai"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } public static void main(String[] args) { EmailClient ec = new EmailClient(); ec.init(); } }
运行展示
在线云笔记
在线云笔记开发并未完成,需要把用户名和密码储存在文件中,将代码中的查询数组操作替换成文件读取操作即可。
客户端窗口
import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; public class Client extends JFrame{ //创建客户端笔记显示窗口 private JTextArea Show = new JTextArea(46,35); private JTextArea List = new JTextArea(46,18); private JTextArea Note = new JTextArea(46,18); //创建登录按钮 private JButton login = new JButton("Login"); private JButton sign = new JButton("Sign"); //创建功能按钮 private JButton create = new JButton("CreateNote"); private JButton save = new JButton("SaveNote"); private JButton upload = new JButton("UpLoad"); private JButton open = new JButton("OpenNote"); private JButton del = new JButton("DeleteNote"); private JButton find = new JButton("FindNote"); private JButton download = new JButton("DownloadNote"); private JPanel btnTool = new JPanel(new GridLayout(7,1)); private JPanel logbtnTool = new JPanel(); private JPanel textTool = new JPanel(); private JPanel kong1 = new JPanel(); private JPanel kong2 = new JPanel(); //设置功能按钮是否被按下 private int issave = 0; private int isopen = 0; private int isdel = 0; private int isfind = 0; private int isupload = 0; private int isdownload = 0; //设置时间 private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置传输文本 private String str = ""; //设置用户名密码 private String username = ""; private String pwd = ""; private int islogin = 0; private int issign = 0; private String note = ""; private boolean isright = false; //设置socket private Socket cs = null; private DataOutputStream dos = null; private DataInputStream dis = null; //登录界面 public void init() { //设置窗口标题,位置和大小 this.setTitle("ClientView"); this.setBounds(300, 300, 900, 750); List.setText("文件列表n"); Note.setText("事件通知n"); //设置文本显示窗口位置 textTool.add(List); kong1.setBounds(0, 0, 30,600); textTool.add(kong1); textTool.add(Note); kong1.setBounds(0, 9, 30,600); textTool.add(kong2); textTool.add(Show); this.add(textTool,BorderLayout.EAST); //设置按钮大小 create.setBounds(0, 0, 50, 100); save.setBounds(0, 100, 50, 100); open.setBounds(0, 200, 50, 100); del.setBounds(0, 300, 50, 100); find.setBounds(0, 400, 50, 100); download.setBounds(0, 500, 50, 100); //布局按钮 btnTool.add(create); btnTool.add(save); btnTool.add(open); btnTool.add(del); btnTool.add(find); btnTool.add(upload); btnTool.add(download); this.add(btnTool,BorderLayout.WEST); //关闭输入直到点击创建 Show.setEditable(false); List.setEditable(false); //关闭按键只到登陆成功 create.setEnabled(false ); save.setEnabled(false ); open.setEnabled(false ); del.setEnabled(false ); find.setEnabled(false ); upload.setEnabled(false ); download.setEnabled(false ); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); //建立连接 try { cs = new Socket("127.0.0.1",8888); dos = new DataOutputStream(cs.getOutputStream()); dis = new DataInputStream(cs.getInputStream()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //登录 Login(); //设置按钮监听 create.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //开启输入 Show.setEditable(true); } }); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //请求服务器保存笔记 try { Save(); tanchuang(); } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); open.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //打开笔记 try { Open(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); del.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //删除笔记 try { Del(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); find.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //查找笔记,为每个用户创建一个记录文件名的文件 Find(); } }); upload.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //上传笔记,简单的上传可以实现,想实现资源管理器直接选择文件 Upload(); } }); download.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //下载笔记,简单的下载可以实现,想实现调用资源管理器直接下载 Download(); } }); // try { // cs = new Socket("127.0.0.1",8888); // dos = new DataOutputStream(cs.getOutputStream()); // dis = new DataInputStream(cs.getInputStream()); // } catch (UnknownHostException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } catch (IOException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } } //登录方法 public void Login() { JFrame JF = new JFrame(); JTextArea User = new JTextArea(1,35); JTextArea PWD = new JTextArea(1,35); JTextArea NOTE = new JTextArea(1,35); NOTE.setEditable(false); JPanel JP = new JPanel(new GridLayout(6,1)); JPanel jp1 = new JPanel(); JPanel jp2 = new JPanel(); JPanel jp3 = new JPanel(); JF.setTitle("User Login"); JF.setBounds(300, 300, 400, 200); JP.add(jp1); JP.add(User); JP.add(jp2); JP.add(PWD); JP.add(jp3); JP.add(NOTE); logbtnTool.add(login); logbtnTool.add(sign); JF.add(JP,BorderLayout.NORTH); JF.add(logbtnTool,BorderLayout.SOUTH); JF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JF.setVisible(true); login.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //denglu try { islogin = 8; dos.write(islogin); username = User.getText(); // System.out.println(username ); pwd = PWD.getText(); dos.writeUTF(username); dos.writeUTF(pwd); note = dis.readUTF(); if(note.equals("1")) { create.setEnabled(true ); save.setEnabled(true ); open.setEnabled(true ); del.setEnabled(true ); find.setEnabled(true ); upload.setEnabled(true ); download.setEnabled(true ); JF.setVisible(false); JOptionPane.showMessageDialog(null, "【成功】", "登陆成功", JOptionPane.ERROR_MESSAGE); } else if(note.equals("2")){ JOptionPane.showMessageDialog(null, "【失败】", "登陆失败", JOptionPane.ERROR_MESSAGE); NOTE.setText("重新登陆"); } User.setText(""); PWD.setText(""); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); sign.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //zhuce try { issign = 9; dos.write(issign); username = User.getText(); pwd = PWD.getText(); dos.writeUTF(username); dos.writeUTF(pwd); note = dis.readUTF(); NOTE.setText(note); JOptionPane.showMessageDialog(null, "【成功】", "注册成功", JOptionPane.ERROR_MESSAGE); User.setText(""); PWD.setText(""); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); // if(note == "") { // JOptionPane.showMessageDialog(null, "【FUCK】", "FUCK", JOptionPane.ERROR_MESSAGE); // } } //保存笔记方法 public void Save () throws UnknownHostException, IOException { issave = 1; //获取笔记内容 str = Show.getText(); //传输笔记内容 dos.write(issave); dos.writeUTF(str); Show.setText(""); Show.setEditable(false); } // 确认笔记弹窗方法 public void tanchuang () throws IOException { issave = 2; String savename = JOptionPane.showInputDialog("Please input name"); dos.write(issave); dos.writeUTF(savename); List.append(dis.readUTF()+"n"); Note.append(df.format(new Date())+dis.readUTF()+"创建成功"+"n"); } //打开笔记方法 public void Open () throws IOException { isopen = 3; dos.write(isopen); String openname = JOptionPane.showInputDialog("Please input filename you want to open"); dos.writeUTF(openname); Show.append(dis.readUTF()); Note.append(df.format(new Date())+openname+"读取成功"+"n"); } //删除笔记方法 public void Del () throws IOException { isdel = 4; dos.write(isdel); String delname = JOptionPane.showInputDialog("Please input filename you want to delete"); dos.writeUTF(delname); Note.append(df.format(new Date())+dis.readUTF()); } //查询笔记方法 //查找笔记,为每个用户创建一个记录文件名的文件 public void Find () { } //上传笔记方法 //上传笔记,简单的上传可以实现,想实现资源管理器直接选择文件 public void Upload () { isupload = 6; } //下载笔记方法 //下载笔记,简单的下载可以实现,想实现调用资源管理器直接下载 public void Download () { } public static void main(String[] args) { Client c = new Client(); c.init(); } }
服务器端代码
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.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; public class Server extends JFrame{ //设置服务器窗口——一个框框 JTextArea serverTa = new JTextArea(); //创建服务器窗口——两个按钮 private JPanel btnTool = new JPanel(); private JButton starBtn = new JButton("start"); private JButton stopBtn = new JButton("stop"); //设置服务器端socket的端口号 private static final int PORT = 8888; //创建服务器端socket private ServerSocket ss = null; private Socket s = null; //设置读入数据 private String Str = ""; private String neirong =""; private String name =""; private String resend =""; //设置用户名数组 private String[] User = new String[] {"","","","","","","","","",""}; private String[] PWD = new String[]{"","","","","","","","","",""};//改进,储存在文件中可以永久保存 //设置服务器启动的标志 private boolean isStart = false; private int i = 0; private int k = 0; //初始化服务器窗口 public void init() { //设置窗口标题 this.setTitle("ServerView"); //设置窗口样式 this.add(serverTa,BorderLayout.CENTER); btnTool.add(starBtn); btnTool.add(stopBtn); this.add(btnTool,BorderLayout.SOUTH); //设置窗口总大小 this.setBounds(0, 0, 150, 500); //设置serverTa不可输入 serverTa.setEditable(false); if(isStart) { serverTa.append("Server started.\n"); }else { serverTa.append("Server not start."+"n"); } //监听开始按钮,启动服务器 starBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if(ss==null) { ss=new ServerSocket(PORT); } isStart = true; serverTa.append("Server started."+"n"); }catch(IOException e1) { e1.printStackTrace(); } } }); //监听停止按钮,关闭服务器 stopBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //关机 isStart = false; try { if(s!=null) { s.close(); } if(ss!=null) { ss.close(); } serverTa.append("Server stopped"); System.exit(0); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); //监听窗口(叉号) this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //关机 isStart = false; try { if(s!=null) { s.close(); } if(ss!=null) { ss.close(); } serverTa.append("Server stopped"); System.exit(0); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); this.setVisible(true); try { startServer(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } /*服务器启动方法*/ public void startServer() throws IOException { ss = new ServerSocket(PORT); isStart = true; //判断是点击了哪个按钮做出相应的函数调用 s= ss.accept(); DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); // serverTa.append(s.getInetAddress()+"|"+s.getPort()+"说:"+ String.valueOf(flag) + "n"); while (isStart) { int flag = dis.read(); switch (flag) { case 1: Str = dis.readUTF(); Receive(Str); break; case 2: Str = dis.readUTF(); Save(Str); Write (neirong,name); dos.writeUTF(resend); dos.writeUTF(resend); break; case 3: Str = dis.readUTF(); Open(Str); dos.writeUTF(resend); break; case 4: Str = dis.readUTF(); i = Del(Str); if(i==0) dos.writeUTF("文件删除成功n"); dos.writeUTF("文件删除失败n"); break; case 5: break; case 6: break; case 7: break; case 8: Check(dis,dos); break; case 9: Add(dis,dos); break; default: break; } } } public static String getType(Object o) { //获取变量类型方法 return o.getClass().toString(); //使用int类型的getClass()方法 } public void Check(DataInputStream Dis,DataOutputStream Dos) { //在数组中找到name,在对应数组中找到pwd检查; String u = ""; String p = ""; int m = 0; try { u = Dis.readUTF(); p = Dis.readUTF(); // System.out.println(getType(u)); // System.out.println(getType(User[2])); // if(u.equals(User[2])) { // System.out.println(User[2]); // } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for(int j=0;j < 10;j++) { if(User[j].equals(u) && PWD[j].equals(p)&& (!u.equals(""))) { k = 1; m=j; break; } else { // System.out.println(j+"----"); } } try { if(k == 1) { serverTa.append(u+m+"用户登陆成功" + "n"); Dos.writeUTF("1"); } else { serverTa.append(u+m+"用户登陆失败" + "n"); Dos.writeUTF("2"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //注册 public void Add(DataInputStream Dis,DataOutputStream Dos) { String u = ""; String p = ""; int n = 0; try { u = Dis.readUTF(); p = Dis.readUTF(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for(int j = 0;j<10;j++) { if(User[j].equals("")) { User[j] = u; PWD[j] = p; n = j; serverTa.append(u+n+"用户注册成功" + "n"); break; } else { continue; } } try { Dos.writeUTF("注册成功"); System.out.println("成功"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //服务器接受数据方法 public void Receive(String restr) { //保存输入信息为文件 neirong = restr; serverTa.append("文件内容:"+restr + "n"); System.out.println(s.getInetAddress()+"|"+s.getPort()+"说:"+restr + "n"); } //接受文件名 public void Save (String restr) { //保存输入信息为文件名 name = restr; serverTa.append("文件名:"+restr + "n"); System.out.println(s.getInetAddress()+"|"+s.getPort()+"说:"+restr + "n"); } //保存文件 public void Write (String nei,String nam) { FileWriter writer; try { writer = new FileWriter("E:/"+ nam ); writer.write(nei); writer.flush(); writer.close(); resend = nam; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //打开文件 public void Open (String opnm) throws IOException { serverTa.append("打开文件:"+opnm + "n"); File file = new File("E:/"+opnm); FileInputStream fin = new FileInputStream(file); Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; fin.read(filecontent); String mid = new String(filecontent); resend = mid; fin.close(); // System.out.println(resend); } public int Del (String delnm) { serverTa.append("删除文件:"+delnm + "n"); File file = new File("E:/"+delnm); if(file.delete()){ serverTa.append(file.getName() + " 文件已被删除!"); return 0; }else{ serverTa.append("文件删除失败!"); return 1; } } public static void main(String[] args) { Server se = new Server(); se.init(); } }
运行展示
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算