JAVA编程C/S结构

服务器端传输程序给客户端,客户端运行并传回结果要怎么架构从哪开始写,大概用到哪些功能语句,我是JAVA初学者。如果有谁做过发给我参考代码更好,回答好的加分。能不能把代码发... 服务器端传输程序给客户端,客户端运行并传回结果要怎么架构从哪开始写,大概用到哪些功能语句,我是JAVA初学者。如果有谁做过发给我参考代码更好,回答好的加分。
能不能把代码发到我邮箱2009.pierre@163.com带上百度账号。
菜茑阿八,谢谢你的回答,你的程序只实现了验证用户名密码功能,那其他的功能要怎么添加,比如服务器端让客户端电脑运行某程序该用到哪方面的知识应用?
还有JAVA中socket语句客户端服务器端对应的语句该怎么写。给我几行例子吧,说明作用。
展开
 我来答
菜茑阿八
推荐于2016-11-29 · TA获得超过227个赞
知道小有建树答主
回答量:271
采纳率:0%
帮助的人:130万
展开全部
鉴于你是初学者不要好高骛远!下面的看懂了就行,不懂就翻一下cs模式的书!
1。服务端工程NioServer.java: 采用nio 方式的异步socket通信,不仅可以实现你的服务器还可以让你多学习一下什么是nio
2。客户端工程UserClient.java: 采用Swing技术画了一个简单的UI界面,比较土,原因是我没那么多时间去设计界面,你需要的话可以自己去修改得漂亮点,相信不难

现在贴工程1:
package com.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioServer {
public static final int SERVERPORT=5555;
public static final String USERNAME="wangzhirong";
public static final String PASSWORD="123456";
public static final String ISACK="ACK";
public static final String ISNAK="NAK!";
// Selector selector;//选择器
// SelectionKey key;//key。 一个key代表一个Selector 在NIO通道上的注册,类似主键;
// //取得这个Key后就可以对Selector在通道上进行操作
private ByteBuffer echoBuffer = ByteBuffer.allocate( 1024 );// 通道数据缓冲区
public NioServer(){
}
public static void main(String[] args) throws IOException {
NioServer ns=new NioServer();
ns.BuildNioServer();
}
public void BuildNioServer() throws IOException{
/////////////////////////////////////////////////////////
///////先对服务端的ServerSocket进行注册,注册到Selector ////
/////////////////////////////////////////////////////////
ServerSocketChannel ssc = ServerSocketChannel.open();//新建NIO通道
ssc.configureBlocking( false );//使通道为非阻塞
ServerSocket ss = ssc.socket();//创建基于NIO通道的socket连接
//新建socket通道的端口
ss.bind(new InetSocketAddress("127.0.0.1",SERVERPORT));
Selector selector=Selector.open();//获取一个选择器
//将NIO通道选绑定到择器,当然绑定后分配的主键为skey
SelectionKey skey = ssc.register( selector, SelectionKey.OP_ACCEPT );
////////////////////////////////////////////////////////////////////
//// 接收客户端的连接Socket,并将此Socket也接连注册到Selector ////
///////////////////////////////////////////////////////////////////
while(true){
int num = selector.select();//获取通道内是否有选择器的关心事件
if(num<1){continue; }
Set selectedKeys = selector.selectedKeys();//获取通道内关心事件的集合
Iterator it = selectedKeys.iterator();
while (it.hasNext()) {//遍历每个事件
try{
SelectionKey key = (SelectionKey)it.next();
//有一个新联接接入事件,服务端事件
if ((key.readyOps() & SelectionKey.OP_ACCEPT)
== SelectionKey.OP_ACCEPT) {
// 接收这个新连接
ServerSocketChannel serverChanel = (ServerSocketChannel)key.channel();
//从serverSocketChannel中创建出与客户端的连接socketChannel
SocketChannel sc = serverChanel.accept();
sc.configureBlocking( false );
// Add the new connection to the selector
// 把新连接注册到选择器
SelectionKey newKey = sc.register( selector,
SelectionKey.OP_READ );
it.remove();
System.out.println( "Got connection from "+sc );
}else
//读客户端数据的事件,此时有客户端发数据过来,客户端事件
if((key.readyOps() & SelectionKey.OP_READ)
== SelectionKey.OP_READ){
// 读取数据
SocketChannel sc = (SocketChannel)key.channel();
int bytesEchoed = 0;
while((bytesEchoed = sc.read(echoBuffer))> 0){
System.out.println("bytesEchoed:"+bytesEchoed);
}
echoBuffer.flip();
System.out.println("limet:"+echoBuffer.limit());
byte [] content = new byte[echoBuffer.limit()];
echoBuffer.get(content);
String result=new String(content);
doPost(result,sc);
echoBuffer.clear();
it.remove();
}
}catch(Exception e){}
}
}
}

public void doPost(String str,SocketChannel sc){
boolean isok=false;
int index=str.indexOf('|');
if(index>0){
String name=str.substring(0,index);
String pswd=str.substring(index+1);
if(pswd==null){pswd="";}
if(name!=null){
if(name.equals(USERNAME)
&& pswd.equals(PASSWORD)
){
isok=true;
}else{
isok=false;
}
}else{
isok=false;
}
}else{
isok=false;
}
String result="";
if(isok){
result="ACK";
}else{
result="NAK!";
}
ByteBuffer bb = ByteBuffer.allocate( result.length() );
bb.put(result.getBytes());
bb.flip();
try {
sc.write(bb);
} catch (IOException e) {
e.printStackTrace();
}
bb.clear();
}

}

下面贴工程2
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class UserClient implements ActionListener{
JFrame jf;
JPanel jp;
JLabel label_name;
JLabel label_pswd;
JTextField userName;
JButton jb;
JPasswordField paswrd;
JLabel hintStr;
public UserClient (){
jf=new JFrame("XXX 登陆系统");
jp=new JPanel();
jf.setContentPane(jp);
jf.setPreferredSize(new Dimension(350,220));
jp.setPreferredSize(new Dimension(350,220));
jp.setBackground(Color.gray);
label_name=new JLabel();
label_name.setPreferredSize(new Dimension(150,30));
label_name.setText("请输入帐户(数字或英文):");
userName=new JTextField();
userName.setPreferredSize(new Dimension(150,30));
jp.add(label_name);
jp.add(userName);
label_pswd=new JLabel();
label_pswd.setPreferredSize(new Dimension(150,30));
label_pswd.setText("请输入密码:");
jp.add(label_pswd);
paswrd=new JPasswordField();
paswrd.setPreferredSize(new Dimension(150,30));
jp.add(paswrd);
jb=new JButton("OK");
jb.setPreferredSize(new Dimension(150,30));
jb.setText("确 定");
jb.addActionListener( this);
jp.add(jb);
hintStr=new JLabel();
hintStr.setPreferredSize(new Dimension(210,40));
hintStr.setText("");
hintStr.setForeground(Color.RED);
jp.add(hintStr);
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private String name;
private String pswd;
public void actionPerformed(ActionEvent e) {
name=userName.getText().trim();
pswd=new String(paswrd.getPassword());
if(pswd==null){
pswd="";
}else{
pswd=pswd.trim();
}
if(name!=null && name.length()>0){
hintStr.setText("正在验证客户端,请稍候...");
start();
}
}

OutputStream os;
Socket s;
InputStream is;
public void start(){
//建立联网线程
new Thread(new Runnable(){
public void run() {
try {
s=new Socket("127.0.0.1",5555);
//写
os=s.getOutputStream();
os.write(name.getBytes());
os.write('|');//用户名与密码用"|"分隔
os.write(pswd.getBytes());
os.flush();
//读内容
Thread.sleep(1000);
is=s.getInputStream();
int len=is.available();
System.out.println("len:"+len);
byte[] bytes=new byte[len];
is.read(bytes);
String resut=new String(bytes);
System.out.println("resut:"+resut);
//TODO 这里通过返回结果处理
if(resut.equals("ACK")){
hintStr.setText("验证成功,欢迎光临!");
}else{
paswrd.setText(null);
hintStr.setText("用户名或密码错误,请重新输入");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
// try {
// os.close();
// is.close();
// s.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
}).start();
}

public static void main(String[] args) {
new UserClient();
}

}
Raymondguo008
2009-05-15 · TA获得超过1634个赞
知道小有建树答主
回答量:887
采纳率:100%
帮助的人:470万
展开全部
一个模仿QQ的聊天程序》
运行的时候先运行ChatServer

//ChatServer.java

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
boolean started = false;
ServerSocket ss = null;

List<Client> clients = new ArrayList<Client>();

public static void main(String[] args) {
new ChatServer().start();
}

public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("端口使用中....");
System.out.println("请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}

try {

while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
//dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;

public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}

public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("对方退出了!我从List里面去掉了!");
//e.printStackTrace();
}
}

public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(int i=0; i<clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
//System.out.println(" a string send !");
}
/*
for(Iterator<Client> it = clients.iterator(); it.hasNext(); ) {
Client c = it.next();
c.send(str);
}
*/
/*
Iterator<Client> it = clients.iterator();
while(it.hasNext()) {
Client c = it.next();
c.send(str);
}
*/
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) {
s.close();
//s = null;
}

} catch (IOException e1) {
e1.printStackTrace();
}

}
}

}
}

//ChatClient.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;

TextField tfTxt = new TextField();

TextArea taContent = new TextArea();

Thread tRecv = new Thread(new RecvThread());

public static void main(String[] args) {
new ChatClient().launchFrame();
}

public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {

@Override
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}

});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();

tRecv.start();
}

public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}

/*
try {
bConnected = false;
tRecv.join();
} catch(InterruptedException e) {
e.printStackTrace();
} finally {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
}

private class TFListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
//taContent.setText(str);
tfTxt.setText("");

try {
//System.out.println(s);
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}

}

}

private class RecvThread implements Runnable {

public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("推出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}

}

}
}
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
omdod
2009-05-28
知道答主
回答量:2
采纳率:0%
帮助的人:0
展开全部
阿八的回答已经很完美了 在c/s架构中 要求不高的通信已经可以实现

不过现在这种信息传递已经不是很理想了。现在B/S环境比较实用,要想服务端向浏览器推送信息 比如 客服系统的自动邀请功能 试试ajax 或许能解决问题
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
jrj2330345
2009-05-15 · TA获得超过253个赞
知道小有建树答主
回答量:260
采纳率:0%
帮助的人:85.3万
展开全部
你要是初学者, 我给你 ,你也看不懂,不会用的
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式