java的socket通信(java socket通信)

      最后更新:2022-11-08 07:17:20 手机定位技术交流文章

      java Socket通信原理

      具体如下:首先socket 通信是基于TCP/IP 网络层上的一种传送方式,我们通常把TCP和UDP称为传输层。其中UDP是一种面向无连接的传输层协议。UDP不关心对端是否真正收到了传送过去的数据。如果需要检查对端是否收到分组数据包,或者对端是否连接到网络,则需要在应用程序中实现。UDP常用在分组数据较少或多播、广播通信以及视频通信等多媒体领域。在这里我们不进行详细讨论,这里主要讲解的是基于TCP/IP协议下的socket通信。socket是基于应用服务与TCP/IP通信之间的一个抽象,他将TCP/IP协议里面复杂的通信逻辑进行分装。服务端初始化ServerSocket,然后对指定的端口进行绑定,接着对端口及进行监听,通过调用accept方法阻塞。此时,如果客户端有一个socket连接到服务端,那么服务端通过监听和accept方法可以与客户端进行连接。Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。Java语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程。Java具有简单性、面向对象、分布式、健壮性、安全性、平台独立与可移植性、多线程、动态性等特点。Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。
      我发个图给你,没看懂再留言吧
      通过tcp/IP或者udp进行网络通讯。 如果还要继续深究的话,建议你看看网络协议方面的书籍
      java Socket通信原理

      Java 关于Socket通信对象流传输的问题

      建议采用Tcpmessage,在报文体里写你要传的东西,设置不同的报文头,通过独到的报文头判断你传的是对象是文件
      你的这一段代码从逻辑上来说是没有问题的。建议你贴出更多的代码来! 我建议你不要把socket 和 in 、out的new放过放到这里来。
      建议使用 xml 或JSON 传输内容,而不是直接传输对象
      trAddInfo 中的对象所对应的类实现 Serializable接口。
      Java 关于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 处理下 连不上没有必要继续了吧
      java里socket通信,异常处理问题。

      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如何实现基于TCP协议的socket传输

      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通信

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

          热门文章

          文章分类