java网络编程,怎样在客户端和服务器间实现通信。

java网络编程,怎样在客户端和服务器间实现通信。,第1张

写个简单点的服务器跟客服端就行了我写了个很简单的,只能在一个客户端跟一个服务器通信,在控制台输入下面这个是服务器import javaio;

import javanet;

import javautilScanner;public class Server

{

public static void main(String[] args)

{

try {

ServerSocket server=new ServerSocket(8888);//定义客户端的端口号

Socket client=serveraccept();//定义一个Socket对象

InputStream is=clientgetInputStream();//服务器接受信息输入流,也就是接受从服务器段发送过来的消息

BufferedReader br=new BufferedReader(new InputStreamReader(is));//用bufferedreader包装下输入流

OutputStream os=clientgetOutputStream();//这是用来给服务器发送消息的输出流

PrintStream ps=new PrintStream(os);

Scanner scanner=new Scanner(Systemin);//从键盘输入字符串

boolean flag=true;//定义一个死循环,让服务器不停的接受从客户端发送来的字符串

while(flag)

{

String s=brreadLine();//s是从客户端接受到得字符串

Systemoutprintln(s);

String s2=scannernextLine();//s2是写给客户端的字符串

psprintln(s2); //给客户端发送你写的东西

}

clientclose();

} catch (IOException e) {//try 跟catch你不用管,这是用来处理异常的,就是固定格式

eprintStackTrace();

}

}

} 下面是客户端import javaio;

import javanet;

import javautilScanner;public class Client

{ public static void main(String[] args)

{

try

{

Socket client=new Socket("192168----",8888);//IP地址是个字符串,端口号是个整数,这个端口号要跟前面你写的那个一样,还有IP地址,写你的机器的IP地址

InputStream is=clientgetInputStream();//这边的两个流跟上面服务器的差不多的作用

BufferedReader bf=new BufferedReader(new InputStreamReader(is));

OutputStream os=clientgetOutputStream();

PrintStream ps=new PrintStream(os);

Scanner scanner=new Scanner(Systemin);

boolean flag=true;

while(flag)//这句话可以让客户端不停的说话

{

String s2=scannernextLine();

psprintln(s2);

String s=bfreadLine();

Systemoutprintln(s); }

clientclose();

}

catch (UnknownHostException e)

{

eprintStackTrace();

}

catch (IOException e)

{

eprintStackTrace();

} }}

我想你应该是想问C/S架构中的客户端和服务端

两者最常见的方式是通过Socket方式进行通信。

Socket可以理解成一个电线插座的工作过程:

服务器是电源插件, 客户端是电器

C和S通过电线和指定的插孔进行连接,连上后,S将电力源源不断发送到C, C就可以工作了。 当然C也可以反向发送信息到S。 两者可以相互通信。

在建立的过程中代码有一些不同。

在服务端采用API类是ServerSocket

在客户端采用的API是Socket类

连接建立后,双方都通过连接获取输入和输出流从而实现通信。即: InputStream is=socketgetInputStream();

isread();

连接代码:

S端:

ServerSocket server=null;

try {

server=new ServerSocket(指定的端口);

}catch(Exception e){

Systemoutprintln("不能监听:"+etoString());

}

Socket socket=null;

try {

socket=serveraccept();

InputStream is=socketgetInputStream();

//己通过建立起流,可以读取客户端发来的请求了

//同样也可以发送能过 sokcetgetOutputStream()

}

catch(IOException e){

Systemoutprintln("出错:"+etoString());

}finally{

try {

if(socket!=null){

socketclose();

serverclose();

}

}

catch(IOException e){

eprintStackTrace();

}

}

客户端:

Socket socket=null;

try {

socket=new Socket(url,端口);

//获取输出流,从而向服务端发数据

socketgetOutputStream();

//获取输入流,从而可以读服务端的数据

socketgetInputStream();

}catch(Exception e){

eprintStackTrace();

}

finally{

try {

socketclose();

}

catch(IOException e){

eprintStackTrace();

}

}

服务器端:

import javaawt;

import javaawtevent;

import javaxswing;

import javaio;

import javanet;

import javautilVector;

public class OneToMoreServer extends JFrame implements ActionListener{

JPanel contentPane;

JLabel jLabel2 = new JLabel();

JTextField jTextField2 = new JTextField("4700");

JButton jButton1 = new JButton();

JLabel jLabel3 = new JLabel();

JTextField jTextField3 = new JTextField();

JButton jButton2 = new JButton();

JScrollPane jScrollPane1 = new JScrollPane();

JTextArea jTextArea1 = new JTextArea();

ServerSocket server = null;

Socket socket = null;BufferedReader instr =null;PrintWriter os=null ;

Vector vector=new Vector();

boolean serverRun=true;

boolean clientRun=true;

//Construct the frame

public OneToMoreServer() {

jbInit();

}

class MyThread extends Thread{//该线程负责接收数据

Socket socketI=null;

BufferedReader br=null;

public MyThread(Socket socket)

{

socketI=socket;

}

public void run(){

try{

while(clientRun){

thissleep(100);

br= new BufferedReader(new InputStreamReader(socketIgetInputStream()));

if(brready()){ //检查是否有数据

jTextArea1append("接收到来自客户端("+socketIgetInetAddress()toString()+")的消息: "+brreadLine()+"\n");

}

}

}catch(Exception ex){JOptionPaneshowMessageDialog(null,extoString());}

}

}

public void actionPerformed(ActionEvent e){

if(egetSource()==jButton1){

int port=IntegerparseInt(jTextField2getText()trim());

//监听指定端口

try

{

server = new ServerSocket(port);

new Thread(new ListenClient())start();

}

catch(IOException ex)

{

JOptionPaneshowMessageDialog(null,extoString());

}

}

if(egetSource()==jButton2){

String msg=jTextField3getText()trim();

if(msglength()!=0)

sendData("hello");

}

}

//该线程负责监听指定端口

class ListenClient implements Runnable

{

public void run()

{

try{

if(jButton1getText()trim()equals("侦听")){

jButton1setText("正在侦听");

while(serverRun)

{

Socket socketI=serveraccept();//有客户端连入时建立一个线程监听客户端发送的消息

vectoradd(socketI);

jButton1setText("正在聊天");

jTextArea1append("客户端"+socketIgetInetAddress()toString()+"已经连接到服务器\n");

MyThread t=new MyThread(socketI);

tstart();

}

}

}catch(Exception ex){

JOptionPaneshowMessageDialog(null,extoString());

}

}

}

private void sendData(String s){//发送数据

try{

for(int i=0;i<vectorsize();i++)

{

//怎么广播

//向每个客户端发送一条消息

Socket socket=(Socket)vectorget(i);

os= new PrintWriter(socketgetOutputStream());

osprintln(s);

osflush();

}

}catch(Exception ex){

}

}

private void jbInit() {

contentPane = (JPanel) thisgetContentPane();

contentPanesetLayout(null);

thissetSize(new Dimension(540, 340));

thissetTitle("服务器");

jLabel2setBounds(new Rectangle(22, 27, 72, 28));

jLabel2setText("端口号");

jLabel2setFont(new javaawtFont("宋体", 0, 14));

jTextField2setBounds(new Rectangle(113, 27, 315, 24));

jButton1setBounds(new Rectangle(440, 28, 73, 25));

jButton1setFont(new javaawtFont("Dialog", 0, 14));

jButton1setBorder(BorderFactorycreateEtchedBorder());

jButton1setActionCommand("jButton1");

jButton1setText("侦听");

jLabel3setBounds(new Rectangle(23, 57, 87, 28));

jLabel3setText("请输入信息");

jLabel3setFont(new javaawtFont("宋体", 0, 14));

jTextField3setBounds(new Rectangle(114, 60, 314, 24));

jTextField3setText("");

jButton2setText("广播");

jButton2setActionCommand("jButton1");

jButton2setBorder(BorderFactorycreateEtchedBorder());

jButton2setFont(new javaawtFont("Dialog", 0, 14));

jButton2setBounds(new Rectangle(440, 58, 73, 25));

jScrollPane1setBounds(new Rectangle(23, 92, 493, 189));

contentPaneadd(jTextField2, null);

contentPaneadd(jButton1, null);

contentPaneadd(jLabel3, null);

contentPaneadd(jTextField3, null);

contentPaneadd(jButton2, null);

contentPaneadd(jScrollPane1, null);

contentPaneadd(jLabel2, null);

jScrollPane1getViewport()add(jTextArea1, null);

jButton1addActionListener(this);

jButton2addActionListener(this);

thisaddWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

try{

socketclose();

instrclose();

Systemexit(0);

}catch(Exception ex){

//JOptionPaneshowMessageDialog(null,extoString());

}

}

});

}

public static void main(String arg[]){

JFramesetDefaultLookAndFeelDecorated(true);

OneToMoreServer frm=new OneToMoreServer();

frmsetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

frmsetVisible(true);

}

}

客户端

import javaawt;

import javaawtevent;

import javaxswing;

import javaio;

import javanet;

public class Client extends JFrame implements ActionListener{

JPanel contentPane;

JLabel jLabel1 = new JLabel();

JTextField jTextField1 = new JTextField("127001");

JLabel jLabel2 = new JLabel();

JTextField jTextField2 = new JTextField("4700");

JButton jButton1 = new JButton();

JLabel jLabel3 = new JLabel();

JTextField jTextField3 = new JTextField();

JButton jButton2 = new JButton();

JScrollPane jScrollPane1 = new JScrollPane();

JTextArea jTextArea1 = new JTextArea();

BufferedReader instr =null;

Socket socket = null;

PrintWriter os=null;

public Client() {

jbInit();

}

class MyThread extends Thread{

public void run(){

try{

os=new PrintWriter(socketgetOutputStream());

instr=new BufferedReader(new InputStreamReader(socketgetInputStream()));

while(true)

{

thissleep(100);

if(instrready())

{

jTextArea1append("接收到来自服务器的消息: "+instrreadLine()+"\n");

}

}

}catch(Exception ex){

JOptionPaneshowMessageDialog(null,extoString());

}

}

}

public void actionPerformed(ActionEvent e){

if(egetSource()==jButton1){

String ip=jTextField3getText()trim();

int port=IntegerparseInt(jTextField2getText()trim());

connectServer(ip,port);

}

if(egetSource()==jButton2){

String s=thisjTextField3getText()trim();

sendData(s);

}

}

private void connectServer(String ip,int port){//连接

try{

if(jButton1getText()trim()equals("连接")){

jButton1setText("连接服务器");

socket=new Socket(ip,port);

jButton1setText("正在聊天");

MyThread t=new MyThread();

tstart();

}

}catch(Exception ex){

JOptionPaneshowMessageDialog(this,extoString());

}

}

private void sendData(String s){//发送数据

try{

os = new PrintWriter(socketgetOutputStream());

osprintln(s);

osflush();

thisjTextArea1append("向服务器发送消息:"+s+"\n");

}catch(Exception ex){

JOptionPaneshowMessageDialog(this,extoString());

}

}

private void jbInit() {

contentPane = (JPanel) thisgetContentPane();

jLabel1setFont(new javaawtFont("宋体", 0, 14));

jLabel1setText("服务器名称");

jLabel1setBounds(new Rectangle(20, 22, 87, 28));

contentPanesetLayout(null);

thissetSize(new Dimension(540, 340));

thissetTitle("客户端");

jTextField1setBounds(new Rectangle(114, 26, 108, 24));

jLabel2setBounds(new Rectangle(250, 25, 72, 28));

jLabel2setText("端口号");

jLabel2setFont(new javaawtFont("宋体", 0, 14));

jTextField2setBounds(new Rectangle(320, 27, 108, 24));

jButton1setBounds(new Rectangle(440, 28, 73, 25));

jButton1setFont(new javaawtFont("Dialog", 0, 14));

jButton1setBorder(BorderFactorycreateEtchedBorder());

jButton1setActionCommand("jButton1");

jButton1setText("连接");

jLabel3setBounds(new Rectangle(23, 57, 87, 28));

jLabel3setText("请输入信息");

jLabel3setFont(new javaawtFont("宋体", 0, 14));

jTextField3setBounds(new Rectangle(114, 60, 314, 24));

jButton2setText("发送");

jButton2setActionCommand("jButton1");

jButton2setBorder(BorderFactorycreateEtchedBorder());

jButton2setFont(new javaawtFont("Dialog", 0, 14));

jButton2setBounds(new Rectangle(440, 58, 73, 25));

jScrollPane1setBounds(new Rectangle(23, 92, 493, 189));

contentPaneadd(jLabel1, null);

contentPaneadd(jTextField1, null);

contentPaneadd(jLabel2, null);

contentPaneadd(jTextField2, null);

contentPaneadd(jButton1, null);

contentPaneadd(jLabel3, null);

contentPaneadd(jTextField3, null);

contentPaneadd(jButton2, null);

contentPaneadd(jScrollPane1, null);

jScrollPane1getViewport()add(jTextArea1, null);

jButton1addActionListener(this);

jButton2addActionListener(this);

thisaddWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

try{

socketclose();instrclose();osclose();Systemexit(0);

}catch(Exception ex){

JOptionPaneshowMessageDialog(null,extoString());

}

}

});

}

public static void main(String arg[]){

JFramesetDefaultLookAndFeelDecorated(true);

Client frm=new Client();

frmsetVisible(true);

}

}

一个服务器对多个客户端,你可以这样去实现:在服务器端程序中为每个连接上服务器的客户端开启一个线程。这也就是多线程编程的内容了,至于你说怎么阻止客户端做重复的动作,你可以在客户端运行某个动作时向服务器端发送一个标识符,服务器端用一个变量存储这些标识符,但服务器端在接受一个标识符后,会对存储这些标识符的变量进行遍历,如果这个标识符已经存在,那么表明是一个重复的动作,服务器端就可以禁止接受该重复动作

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » java网络编程,怎样在客户端和服务器间实现通信。

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情