
正文
Java服务器注册代码 java用户注册代码
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
急求一段JAVA代码,有关客户端和服务器的。。。
客户端
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
/**
*
* @author Administrator
*/
public class Main extends JFrame{
JPanel jp;
JButton jb;
javax.swing.JTextField jt1;
JTextField jt2;
JTextField jt3;
JLabel jl1;
JLabel jl2;
public Main()
{
this.setBounds(150, 50, 300, 100);
jp= new JPanel(new GridLayout(3, 2));
jb=new JButton("登陆");
jt1=new JTextField();
jt2=new JTextField();
jt3=new JTextField();
jt3.setEditable(false);
jl1=new JLabel("用户名");
jl2=new JLabel("密码");
this.getContentPane().add(jp);
jp.add(jl1);
jp.add(jt1);
jp.add(jl2);
jp.add(jt2);
jp.add(jt3);
jp.add(jb);
this.setVisible(true);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String sentence;
String modifiedSentence = null;
//BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 6789);
} catch (UnknownHostException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("connection ok");
DataOutputStream outToServer = null;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader inFromServer = null;
try {
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
sentence=jt1.getText()+" "+jt2.getText();
try {
//System.out.println(sentence);
outToServer.writeBytes(sentence + '\n');
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
try {
modifiedSentence = inFromServer.readLine();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("FROM SERVER:"+modifiedSentence);
jt3.setText(modifiedSentence);
try {
clientSocket.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception
{
Main m=new Main();
}
}
服务器端
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket=new ServerSocket(6789);
while(true){
Socket connectionSocket=welcomeSocket.accept();
BufferedReader inFromClient=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient=new DataOutputStream(connectionSocket.getOutputStream());
clientSentence=inFromClient.readLine();
//capitalizedSentence=clientSentence.toUpperCase()+'\r'+'\n';
//outToClient.writeBytes(capitalizedSentence);
if(clientSentence.equalsIgnoreCase("admin 1234"))
outToClient.writeBytes("ok"+'\n');
else
outToClient.writeBytes("error"+'\n');
}
}
}
相关问答
Q1: Java Web服务器
我现写了一个,可以访问到静态资源。你看情况多给点分吧
另外eclipse还没有5.5,5.5的貌似是myEclipse吧
其中port指端口,默认是地址是
其中basePath指资源根路径,默认是d:
可以通过命令行参数对其进行赋值
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
public class SimpleHttpServer {
private static int port = 8088;
private static String basePath = "D:/";
public static void main(String[] args) {
if (args.length = 1) {
basePath = args[0];
}
if (args.length = 2) {
port = Integer.parseInt(args[1]);
}
System.out.println("server starting:");
System.out.println("base path:" + basePath);
System.out.println("Listening at:" + port);
startServer();
System.out.println("server started succesfully");
}
private static void startServer() {
new Thread() {
public void run() {
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
final Socket s = ss.accept();
new Thread() {
public void run() {
try {
OutputStream socketOs = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
String headerLine = null;
while ((line = br.readLine()) != null) {
if (headerLine == null) {
headerLine = line;
}
if ("".equals(line)) {
break;
}
}
String target = headerLine.replaceAll("^.+ (.+) HTTP/.+$", "$1");
String queryString;
String[] tmp = target.split("\\?");
target = URLDecoder.decode(tmp[0], "utf-8");
target = target.endsWith("/") ? target.substring(0, target.length() - 1) : target;
if (tmp.length 1) {
queryString = tmp[1];
} else {
queryString = "";
}
String filePath = basePath + target;
File f = new File(filePath);
if (!f.exists()) {
StringBuffer content = new StringBuffer();
content.append("htmlheadtitleResource Not Found/title/headbodyh1The requested resource ")
.append(target).append(" is not found./h1/body/html");
StringBuffer toWrite = new StringBuffer();
toWrite.append("HTTP/1.1 404 Not Found\r\nContent-Length:").append("" + content.length()).append("\r\n\r\n")
.append(content);
socketOs.write(toWrite.toString().getBytes());
} else if (f.isDirectory()) {
StringBuffer content = new StringBuffer();
content.append("htmlheadtitle").append(target).append(
"/title/headbodytable border='1' width='100%'");
content.append("trth align='left' width='40px'").append("Path").append("/thtd").append(target.length()0?target:"/")
.append("/td/tr");
content.append("trth align='left'Type/thth align='left'Name/th/tr");
if (!basePath.equals(filePath)) {
content.append("trtdDirectory/tdtd").append("a href='").append(
target.substring(0, target.lastIndexOf("/") + 1)).append("'../a").append("/td/tr");
}
File[] files = f.listFiles();
for (File file : files) {
content.append("trtd");
if (file.isFile()) {
content.append("File/tdtd");
} else if (file.isDirectory()) {
content.append("Directory/tdtd");
}
content.append("a href=\"").append(target);
if (!(target.endsWith("/") || target.endsWith("\\"))) {
content.append("/");
}
content.append(file.getName()).append("\"").append(file.getName()).append("/a/td/tr");
}
content.append("/table/body/html");
StringBuffer sb = new StringBuffer();
sb.append("HTTP/1.1 200 OK\r\nCache-Control: max-age-0\r\n");
sb.append("Content-Length:").append("" + content.length()).append("\r\n\r\n");
sb.append(content);
socketOs.write(sb.toString().getBytes());
} else if (f.isFile()) {
socketOs.write(("HTTP/1.1 200 OK\r\nCache-Control: max-age-0\r\nContent-Length:" + f.length() + "\r\n\r\n")
.getBytes());
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(f);
int cnt = 0;
while ((cnt = fis.read(buffer)) = 0) {
socketOs.write(buffer, 0, cnt);
}
fis.close();
}
socketOs.close();
} catch (Exception e) {
try {
s.getOutputStream().write("HTTP/1.1 500 Error\r\n".getBytes());
ByteArrayOutputStream byteos = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(byteos);
printStream
.write("htmlheadtitleError 500/title/headbodyh1Error 500/h1pre style='font-size:15'"
.getBytes());
e.printStackTrace(printStream);
printStream.write("/prebody/html".getBytes());
byteos.close();
byte[] byteArray = byteos.toByteArray();
s.getOutputStream().write(("Content-Length:" + byteArray.length + "\r\n\r\n").getBytes());
s.getOutputStream().write(byteArray);
s.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
Q2: 关于java,soap服务器端的代码怎么写
soapenv:Header/
soapenv:Body
api:getEmp
shopIdstring/shopId
/api:getEmp
/soapenv:Body
/soapenv:Envelope
这个时SOAP协议的标准报文格式,客户端只要发送这样的报文给支持SOAP协议的webservice服务器即可成功调用web service服务
服务端:部署服务只需要自己定义服务的接口和实现类,并用@webservice注解,通过endPoint类直接发布即可
Q3: Java中怎么注册协议
注册协议
URL的static URLStreamHandler getURLStreamHandler(String protocol) 方法用于获取获取协议处理类
URL提供了两种注册协议的途径。
1)设置URLStreamHandlerFactory,2)设置jvm启动参数java.protocol.handler.pkgs。
两者可以同时使用。
设置URLStreamHandlerFactory
URL的方法
public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) {
synchronized (streamHandlerLock) {
if (factory != null) {
throw new Error("factory already defined");
}
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkSetFactory();
}
handlers.clear();
factory = fac;
}
}
public interface URLStreamHandlerFactory {
URLStreamHandler createURLStreamHandler(String protocol);
}
整个jvm只能设置一次,再次设置不起作用。调用URL.setURLStreamHandlerFactory(fac)。
一般是在服务器的代码中设置,比如tomcat,jboss ,was等,用于注册服务器自己的协议,应用级没法设置,因为服务器已经设置过了,应用即使设置了也不起作用。
启动参数-Djava.protocol.handler.pkgs
通过-Djava.protocol.handler.pkgs=cn.ccb.wfcp注册自定义协议的包。要求协议处理类的类名必须是Handler,包名的最后是协议名。示例如下,定义了brules协议。
package cn.ccb.wfcp.brules;
public class Handler extends URLStreamHandler {
如果要定义多个协议包就用"|"分割,比如-Djava.protocol.handler.pkgs=cn.ccb.wfcp|cn.ccb.wfcp22.
jvm内置的协议也是按照上面的方式定义的,但不用通过-Djava.protocol.handler.pkgs注册,而是将内置的协议包拼接到后面。内置协议都在sun.net.包下面。
获取到Handler类名后去加载class。Class cls = null;
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException e) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
cls = cl.loadClass(clsName);
}
}
if (cls != null) {
handler =
(URLStreamHandler)cls.newInstance();
}
Q4: Java 做一个用户注册登录平台,要求不用数据库,直接用建个简单的服务器,用多线程和xml写
xml文件
db
username/namepwd/pwd/user
username/namepwd/pwd/user
/db
登陆注册都需要解析xml文件
注册的时候往xml文件插入一个user节点
登陆的时候遍历所有节点
Q5: java实现登陆和注册验证,用到多线程!
你说的C/S结构,那么你会使用socket不??
服务器的serversocket,每accept()得到一个socket,就启动一个线程即可。
例如在server中,
ServerSocket server;
/*此处省略初始化等*/
public void handle()throws Eception{
while(true){
Socket socket=server.accept();
new Thread(new HandleThread(socket)).start();
}
}
然后弄个HandleThread的实现Runnable的类
class HandleThread implements Runnable{
private Socket socker;
public HandleThread(Socket s){
socket=s;
}
public void run(){
//在这里写你要处理的东西即可
}
}
关于Java服务器注册代码和java用户注册代码的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。







