java客户端与服务器,第1张

package server;

import javaio;

import javanet;

public class ServerVieew {

public static void main(string []args) throws IOException{ //你少了参数啊,这个是入口地址,没有参数当然不能运行了

ServerSocket ss = new ServerSocket(8888); //创建ServerSocket对象

//调用ServerSocket方法中的accept()方法

Socket s = ssaccept();

//调用Socket中的getInputStream()方法得到输入流

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

//调用Socket对象的getOutputStream()方法得到输出流

PrintWriter pw = new PrintWriter(new OutputStreamWriter(sgetOutputStream()));

String str = "";

//读取从客户端传过来的数据并发送到客户端

while((str = brreadLine())!= null){

pwprint(str);

pwflush();

}

//关闭连接

brclose();

pwclose();

sclose();

ssclose();

}

}

1、服务端监听一个端口,其它客户端都通过这个端口和服务端进行通信。

2、每个客户端连接上来,服务端给其一个标识ID。然后向其它所有客户端广播一下有新客户端接入,ID多少。

3、客户端要向客户端发送消息,可以以消息包的形式发送,就是把目的客户端的标识和发送的内容组成一个数据包发往服务器,服务器读取就知道要向哪 个客户端发送数据,然后把内容往目的客户端通道发送

写个简单点的服务器跟客服端就行了我写了个很简单的,只能在一个客户端跟一个服务器通信,在控制台输入下面这个是服务器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();

} }}

你说得太笼统了,问题不好分析,类似这种问题大概可以从以下几个方面来分析:

1确认客户端访问的IP正确

2首先要确认客户端和java服务器之间的消息通信通道否畅通,如果你的客户端是在PC上,可以直接在PC中ping那台java服务器,看是否能ping通(可能有防火墙,或者IP段限制导致无法连通)

3如果消息通道是畅通的,你需要通过抓包或者日志跟踪,消息是在哪一步丢失的,在java服务器端,如果是linxu系统,通过tcpdump抓包分析(可以抓到客户端的请求和回应),在客户端一般只能通过日志跟踪了

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

服务器端:

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);

}

}

下面是一个简单的通讯实例,进行Server和Client之间的文件传输。。如果是简单的文本传输的话简化掉文本操作的内容即可。。

1服务器端

package sterning;

import javaioBufferedInputStream;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioFile;

import javaioFileInputStream;

import javanetServerSocket;

import javanetSocket;

public class ServerTest {

int port = 8821;

void start() {

Socket s = null;

try {

ServerSocket ss = new ServerSocket(port);

while (true) {

// 选择进行传输的文件

String filePath = "D:\\librar";

File fi = new File(filePath);

Systemoutprintln("文件长度:" + (int) filength());

// public Socket accept() throws

// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。

s = ssaccept();

Systemoutprintln("建立socket链接");

DataInputStream dis = new DataInputStream(new BufferedInputStream(sgetInputStream()));

disreadByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));

DataOutputStream ps = new DataOutputStream(sgetOutputStream());

//将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。

pswriteUTF(figetName());

psflush();

pswriteLong((long) filength());

psflush();

int bufferSize = 8192;

byte[] buf = new byte[bufferSize];

while (true) {

int read = 0;

if (fis != null) {

read = fisread(buf);

}

if (read == -1) {

break;

}

pswrite(buf, 0, read);

}

psflush();

// 注意关闭socket链接哦,不然客户端会等待server的数据过来,

// 直到socket超时,导致数据不完整。

fisclose();

sclose();

Systemoutprintln("文件传输完成");

}

} catch (Exception e) {

eprintStackTrace();

}

}

public static void main(String arg[]) {

new ServerTest()start();

}

}

2socket的Util辅助类

package sterning;

import javanet;

import javaio;

public class ClientSocket {

private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {

thisip = ip;

thisport = port;

}

/ //

创建socket连接

@throws Exception

exception

/

public void CreateConnection() throws Exception {

try {

socket = new Socket(ip, port);

} catch (Exception e) {

eprintStackTrace();

if (socket != null)

socketclose();

throw e;

} finally {

}

}

public void sendMessage(String sendMessage) throws Exception {

try {

out = new DataOutputStream(socketgetOutputStream());

if (sendMessageequals("Windows")) {

outwriteByte(0x1);

outflush();

return;

}

if (sendMessageequals("Unix")) {

outwriteByte(0x2);

outflush();

return;

}

if (sendMessageequals("Linux")) {

outwriteByte(0x3);

outflush();

} else {

outwriteUTF(sendMessage);

outflush();

}

} catch (Exception e) {

eprintStackTrace();

if (out != null)

outclose();

throw e;

} finally {

}

}

public DataInputStream getMessageStream() throws Exception {

try {

getMessageStream = new DataInputStream(new BufferedInputStream(socketgetInputStream()));

return getMessageStream;

} catch (Exception e) {

eprintStackTrace();

if (getMessageStream != null)

getMessageStreamclose();

throw e;

} finally {

}

}

public void shutDownConnection() {

try {

if (out != null)

outclose();

if (getMessageStream != null)

getMessageStreamclose();

if (socket != null)

socketclose();

} catch (Exception e) {

}

}

}

3客户端

package sterning;

import javaioBufferedOutputStream;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioFileOutputStream;

public class ClientTest {

private ClientSocket cs = null;

private String ip = "localhost";// 设置成服务器IP

private int port = 8821;

private String sendMessage = "Windwos";

public ClientTest() {

try {

if (createConnection()) {

sendMessage();

getMessage();

}

} catch (Exception ex) {

exprintStackTrace();

}

}

private boolean createConnection() {

cs = new ClientSocket(ip, port);

try {

csCreateConnection();

Systemoutprint("连接服务器成功!" + "\n");

return true;

} catch (Exception e) {

Systemoutprint("连接服务器失败!" + "\n");

return false;

}

}

private void sendMessage() {

if (cs == null)

return;

try {

cssendMessage(sendMessage);

} catch (Exception e) {

Systemoutprint("发送消息失败!" + "\n");

}

}

private void getMessage() {

if (cs == null)

return;

DataInputStream inputStream = null;

try {

inputStream = csgetMessageStream();

} catch (Exception e) {

Systemoutprint("接收消息缓存错误\n");

return;

}

try {

//本地保存路径,文件名会自动从服务器端继承而来。

String savePath = "E:\\";

int bufferSize = 8192;

byte[] buf = new byte[bufferSize];

int passedlen = 0;

long len=0;

savePath += inputStreamreadUTF();

DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(newBufferedOutputStream(new FileOutputStream(savePath))));

len = inputStreamreadLong();

Systemoutprintln("文件的长度为:" + len + "\n");

Systemoutprintln("开始接收文件!" + "\n");

while (true) {

int read = 0;

if (inputStream != null) {

read = inputStreamread(buf);

}

passedlen += read;

if (read == -1) {

break;

}

//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比

Systemoutprintln("文件接收了" + (passedlen 100/ len) + "%\n");

fileOutwrite(buf, 0, read);

}

Systemoutprintln("接收完成,文件存为" + savePath + "\n");

fileOutclose();

} catch (Exception e) {

Systemoutprintln("接收消息错误" + "\n");

return;

}

}

public static void main(String arg[]) {

new ClientTest();

}

}

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » java客户端与服务器

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情