java socket实现两个客户段或多个客户端之间通信,该怎么解决
javasocket有两种方式。一种是UDP这个可以直连,不需要服务器。一种是TCP这个是肯定要能过服务器来通信的。所以你说的。链接建立完毕后不再通过服务器!这个可以实现,但会麻烦一些。1.先说一下简单的点的吧。用TCP的方式。你所有的消息都是发给服务器。包含你的IP及通信端口,及对方的IP及通信端口信息。当然这些是隐藏在数据报中的。这样由服务器来进行分发。2.你说的那种方式有点类似TCP与UDP混合。首先启动一个SERVER然后每一个客户端,先要登陆SERVER,并在server上记录下你的IP及通信端口信息,如果你要连接某一个客户端。先要向服务器发出一个申请,获得到方的IP及端口信息,然后进行UDP连接。连接上以后,就是直接发送息,不需要服务器了。javasocket的东西,以前做过一些,所以有思路,但没有现成的代码。有问题再联系。

java中Socket通信
你加了高分我才贴 ----------------具体是: Client-A发送消息向Server:消息包括内容+流向(Client-B的地址)+消息来源地址 Server接收后再把消息+来源地址发给Client-B
两个文件都给你 肯定没有错的//ChatServer.javaimport java.io.*;import java.net.*;import java.util.*;public class ChatServer {boolean started = false;ServerSocket ss = null;List clients = new ArrayList();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 blocke.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 it = clients.iterator(); it.hasNext(); ) {Client c = it.next();c.send(str);}*//*Iterator 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.javaimport 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() {@Overridepublic 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();}}} }
看看这个怎么样: import java.io.*;import java.net.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.*;import ccit.Message;public class Server extends Thread{public static final int PORT = 1112;Socket socket;ServerSocket serverSocket;static Vector usrList=new Vector(1,1);public Server(){try{serverSocket=new ServerSocket(PORT);}catch(IOException ioe){System.out.println("Can't set up server socket."+ioe);}System.out.println("server start ...");this.start();}public void run(){try{while (true){System.out.println("正在等待连接.....");socket = serverSocket.accept();//PrintWriter pw=new PrintWriter(socket.getOutputStream());//pw.println("aaa");usrThread ut=new usrThread(socket);usrList.addElement(ut);}}catch(IOException ioe1){System.out.println("Can't set up user thread"+ioe1);}}public static void main(String args[]){Server sobj=new Server();}}class usrThread extends Thread{Socket socket;ObjectInputStream osFromClient;ObjectOutputStream osToClient;thPut tp;thGet tg;static int msgCount=0;static Vector msgBox = new Vector(1,1);int localCount=0;public synchronized void writeMsg(Message msg){msgBox.addElement(msg);msgCount++;}public synchronizedMessage readMsg(){Message msg=(Message)(msgBox.elementAt(localCount));return msg;}public usrThread(Socket s){socket=s;try{osFromClient=new ObjectInputStream(socket.getInputStream());osToClient=new ObjectOutputStream(socket.getOutputStream());System.out.println("osToClient and osFromClient finished!");this.start();tp=new thPut();tp.start();tg=new thGet();tg.start();}catch(Exception e){System.out.println("usrThread init error! "+e);}}public void run(){}class thPut extends Thread{Message msg;public void run(){try{while(true){msg = (Message)osFromClient.readObject();writeMsg(msg);System.out.println(msg.fromname+" says: "+msg.message);}}catch(Exception e){System.out.println("Receive error"+e);}}}class thGet extends Thread{//Declare the currnet message get from readMsg methodMessage msg=new Message();public void run(){try{while(true){while (localCount>=msgCount){this.sleep(1);}msg=readMsg();System.out.println("Write to "+msg.toname);osToClient.writeObject(msg);System.out.println(String.valueOf(localCount));localCount++;}}catch(Exception e){System.out.println("cant write msg to client"+e);}}}}客户端代码:import java.io.*;import java.net.*;import java.util.*;import java.awt.*;import javax.swing.*;import java.awt.event.*;import ccit.Message;public class ClientChat extends JFrame{static long sum;JLabel lpublic=new JLabel("公共聊天区");JLabel lprivate=new JLabel("私人聊天区");JLabel lgetlist=new JLabel("在线用户");JTextArea taPublicMsg=new JTextArea(10,15);JTextArea taPrivateMsg=new JTextArea(6,10);JTextField tfSendMsg=new JTextField(40);JButton bsend=new JButton("发送");JButton bexit=new JButton("退出");JPanel pLabelPub=new JPanel();JPanel pLabelPri=new JPanel();Vector userVector=new Vector(1,1);JList userList=new JList();Socket socket=null;String name;ObjectOutputStream oos=null;ObjectInputStream ois=null;public ClientChat(String name){JScrollPane scrpPub=new JScrollPane(taPublicMsg);pLabelPub.setLayout(new BorderLayout());pLabelPub.add(lpublic,BorderLayout.NORTH);pLabelPub.add(scrpPub,BorderLayout.CENTER);JScrollPane scrpPri=new JScrollPane(taPrivateMsg);pLabelPri.setLayout(new BorderLayout());pLabelPri.add(lprivate,BorderLayout.NORTH);pLabelPri.add(scrpPri,BorderLayout.CENTER);JPanel pGetMsg=new JPanel();pGetMsg.setLayout(new GridLayout(3,1,5,5));pGetMsg.add(pLabelPub);//pGetMsg.add(taPublicMsg);pGetMsg.add(pLabelPri);//pGetMsg.add(taPrivateMsg);JPanel pSendMsg=new JPanel();pSendMsg.setLayout(new FlowLayout());pSendMsg.add(tfSendMsg);pSendMsg.add(bsend);pSendMsg.add(bexit);pGetMsg.add(pSendMsg);userVector.addElement("To All");userList.setListData(userVector);JScrollPane scrpList=new JScrollPane(userList);JPanel pGetList=new JPanel();pGetList.setLayout(new BorderLayout());pGetList.add(lgetlist,BorderLayout.NORTH);pGetList.add(scrpList,BorderLayout.CENTER);this.getContentPane().setLayout(new BorderLayout());this.getContentPane().add(pGetMsg,BorderLayout.CENTER);this.getContentPane().add(pGetList,BorderLayout.EAST);this.setTitle("小桥流水(花语)聊天室(在线用户"+(++sum)+"位)");this.setSize(500,300);this.setVisible(true);this.name=name;//this.socket=socket;try{System.out.println("正在连接.....");InetAddress addr = InetAddress.getByName(null);System.out.println("addr = " + addr);//socket = new Socket(addr,Server.PORT);//socket = new Socket("127.0.0.1",1112);ois=new ObjectInputStream(socket.getInputStream());oos=new ObjectOutputStream(socket.getOutputStream());//PrintWriter pw=new PrintWriter(oos);Message msgLogin=new Message("To All",name,"Login","Login");//pw.print(msgLogin);oos.writeObject(msgLogin);new manageThread().start();}catch(Exception e){System.out.println("JFtame error:"+e);}}public class sendListener implements ActionListener{public void actionPerformed(ActionEvent evt){Message getMsg=new Message();getMsg.toname=userList.getSelectedValue().toString();getMsg.fromname=name;getMsg.message=tfSendMsg.getText();getMsg.command="chat";try{oos.writeObject(getMsg);}catch(Exception e){System.out.println("Send:"+getMsg.message);}}}public class exitListener implements ActionListener{public void actionPerformed(ActionEvent evt){Message getMsg=new Message("To All",name,"","Logout");try{oos.writeObject(getMsg);}catch(Exception e){System.out.println(e);}ClientChat.this.setVisible(false);}}public class manageThread extends Thread{Message GetMessage;public void run(){while(true){try{GetMessage=(Message)ois.readObject();if(GetMessage.command.equals("Login")){userVector.addElement(GetMessage.fromname);userList.setListData(userVector);taPublicMsg.append(GetMessage.fromname+"has arrived!n");}if(GetMessage.command.equals("Logout")){int i=0;for(i=0;i

java 中socket实现通信的原理
1. 所谓Javasocket通信通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过"套接字"向网络发出请求或者应答网络请求。2.socket开发分客户端与服务端3.服务端开启服务监听某一端口4.客户端向此服务器的这个端口发出请求,成功则会建立会话,形成通道.5. 这个通道若不做其它操作会一直存在,就是所谓的长连接了,这时服务端与客户端可以通过此通道进行即时通信

Java 关于Socket通信对象流传输的问题
建议采用Tcpmessage,在报文体里写你要传的东西,设置不同的报文头,通过独到的报文头判断你传的是对象是文件
你的这一段代码从逻辑上来说是没有问题的。建议你贴出更多的代码来! 我建议你不要把socket 和 in 、out的new放过放到这里来。
建议使用 xml 或JSON 传输内容,而不是直接传输对象
trAddInfo 中的对象所对应的类实现 Serializable接口。

Java的Socket编程?
要通信首先要建立socket链接。 1 ab客户端与服务端建立socket链接2 a客户端发送消息到服务端3 服务端收到消息后,发送到指定的b客户端 4 b客户端处理来自服务端的消息

本文由 在线网速测试 整理编辑,转载请注明出处,原文链接:https://www.wangsu123.cn/news/43771.html。