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是什么意思?
所谓socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过"套接字"向网络发出请求或者应答网络请求。 以J2SDK-1.3为例,Socket和ServerSocket类库位于java.net包中。ServerSocket用于服务器端,Socket是建立网络连接时使用的。在连接成功时,应用程序两端都会产生一个Socket实例,操作这个实例,完成所需的会话。对于一个网络连接来说,套接字是平等的,并没有差别,不因为在服务器端或在客户端而产生不同级别。不管是Socket还是ServerSocket它们的工作都是通过SocketImpl类及其子类完成的。重要的Socket API:java.net.Socket继承于java.lang.Object,有八个构造器,其方法并不多,下面介绍使用最频繁的三个方法,其它方法大家可以见JDK-1.3文档。. Accept方法用于产生"阻塞",直到接受到一个连接,并且返回一个客户端的Socket对象实例。"阻塞"是一个术语,它使程序运行暂时"停留"在这个地方,直到一个会话产生,然后程序继续;通常"阻塞"是由循环产生的。. getInputStream方法获得网络连接输入,同时返回一个InputStream对象实例。. getOutputStream方法连接的另一端将得到输入,同时返回一个OutputStream对象实例。注意:其中getInputStream和getOutputStream方法均会产生一个IOException,它必须被捕获,因为它们返回的流对象,通常都会被另一个流对象使用。2ServerSocket类例子编辑package com.lanber.socket;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class ServerDemo {/*** 注意:Socket的发送与接收是需要同步进行的,即客户端发送一条信息,服务器必需先接收这条信息,* 而后才可以向客户端发送信息,否则将会有运行时出错。* @param args*/public static void main(String[] args) {ServerSocket ss = null;try {ss = new ServerSocket(8888);//服务器接收到客户端的数据后,创建与此客户端对话的SocketSocket socket = ss.accept();//用于向客户端发送数据的输出流DataOutputStream dos = new DataOutputStream(socket.getOutputStream());//用于接收客户端发来的数据的输入流DataInputStream dis = new DataInputStream(socket.getInputStream());System.out.println("服务器接收到客户端的连接请求:" + dis.readUTF());//服务器向客户端发送连接成功确认信息dos.writeUTF("接受连接请求,连接成功!");//不需要继续使用此连接时,关闭连接socket.close();ss.close();} catch (IOException e) {e.printStackTrace();}}}3客户端的例子编辑package com.lanber.socket;importjava.io.DataInputStream;import java.io.DataOutputStream;importjava.io.IOException;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class ClientDemo {/*** @param args*/public static void main(String[] args) {Socket socket = null;try {socket = new Socket("localhost",8888);//获取输出流,用于客户端向服务器端发送数据DataOutputStream dos = new DataOutputStream(socket.getOutputStream());//获取输入流,用于接收服务器端发送来的数据DataInputStream dis = new DataInputStream(socket.getInputStream());//客户端向服务器端发送数据dos.writeUTF("我是客户端,请求连接!");//打印出从服务器端接收到的数据System.out.println(dis.readUTF());//不需要继续使用此连接时,记得关闭哦socket.close();} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} }

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

java如何实现基于TCP协议的socket传输
服务端监听:ServerSocket server=newServerSocket(port);//port:绑定的端口号Socketclient=server.accept();//监听端口,一旦取得连接则获得客户端的socket连接对象client客户端:Sockets=newSocket(ip,port);//要连接的服务器的ip以及端口号如果正常连接上之后,socket的对象可以获得InputStream和OutputStreame,然后就可以进行通信了 完成通信之后,执行socket对象的close()方法关闭连接,完成一次完整的socket连接

java里socket通信,异常处理问题。
直接用这种方式处理:while(true){socket = new Socket(("192.168.183.1", 9002);socket.setSoTimeout(5000);//5000ms = 5stry{socket.connect();}catch(IOException e){//这行写你提示通信失败提示continue;}}
在建立socket连接时设置超时时间,连接不上的话就反馈连接失败不就可以了嘛
try catch 处理下 连不上没有必要继续了吧

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