JAVA客户端与服务端Socket通信问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA客户端与服务端Socket通信问题相关的知识,希望对你有一定的参考价值。

本地两个程序TCPCLIENT与TCPSerVER
Client:

import java.net.*;
import java.io.*;
public class TCPclient
public static void main(String[] args)
InputStream is=null;
OutputStream os=null;
try

Socket s=new Socket("127.0.0.1",6666);
is=s.getInputStream();
os=s.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
dos.writeUTF("hello server");
dos.flush();
if(dis.readUTF()!=null)
System.out.println(dis.readUTF()+"FROM"+s.getInetAddress()+"#"+s.getPort());

dos.close();
dis.close();
s.close();

catch(Exception e)





/////////////////////////////////////////////////////////////////////////////////////////
Server:
import java.net.*;
import java.io.*;

public class TCPserver
public static void main(String[] args)
InputStream is=null;
OutputStream os=null;
try
ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept();
os=s.getOutputStream();
is=s.getInputStream();
DataOutputStream dos=new DataOutputStream(os);
DataInputStream dis=new DataInputStream(is);
if(dis.readUTF()!=null)
System.out.println(dis.readUTF()+"from:"+s.getInetAddress()+"#"+s.getPort());

dos.writeUTF("hello client");
dis.close();
dos.close();
ss.close();


catch(Exception e)




本来互相之间应该接受到消息的,但是服务端启动后再启动客户端,客户端出现了阻塞,都没有了消息

你就发了一句话,怎么能接受两遍呢


改成这样 String lin=null;

                if((lin=dis.readUTF())!=null)

                        System.out.println(lin);

                    

这样试试

参考技术A 你这很明显会抛异常啊
你把异常打印出来看看
你把 dis.readUTF()删掉 应该能跑起来 但是这也是不符合Socket通信的经典写法的 网上有很多Socket通信的例子 LZ可以看看
参考技术B 你把dos.flush();去掉试试追问

还是没有效果。我debug client程序,在if那里就走不动了,但是也没提示任何信息

追答

好久没玩java se了 我就记得当时写这个的时候,的确是有一个地方要注意,就是有个流占了通道,让他放了就可以

java 界面编程用socket实现服务端与客户端的循环通信。

服务端:

package 实验五聊天;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;


import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class 服务端 extends JFrame implements  Runnable {

    private JPanel contentPane;
    private JTextField textField;
    private  static JTextArea BtextArea;
    public static ServerSocket serverSocket=null;
    public static Socket clientSocket=null;
    //public static PrintWriter out=null;
    public static DataOutputStream out=null;
    public static DataInputStream in=null;
        public void run()//接收信息
        {
            try
            {
                while(true)
                {
                    if(in!=null)
                        {
                            String tmp=in.readUTF();
                            BtextArea.append("\\n客户端:\\n"+tmp);
                        }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }    
        }
    private Thread thread;
    public void connect()
    {
        try
        {
            serverSocket =new ServerSocket(8000);
            clientSocket=serverSocket.accept();
            in=new DataInputStream(clientSocket.getInputStream());
            out=new DataOutputStream(clientSocket.getOutputStream());
            System.out.println("链接成功");
            if (!(thread.isAlive())) { 
                thread = new Thread(this);
            }
            thread.start();
        }
        catch(Exception e)
        {
            System.out.println("连接失败");
            e.printStackTrace();
        }
        
    }
    public void send()
    {
        try
        {
            String tmp=textField.getText();
            textField.setText("");
            if(tmp.isEmpty())
            {
                JOptionPane.showMessageDialog(this, "请输入信息");
                return;
            }
            BtextArea.append("\\n服务端:\\n"+tmp);
                 if(out!=null)
                     {
                         out.writeUTF(tmp);
                     }
                 else
                 {
                     System.out.println("链接未建立");
                 }
        }
        catch(Exception e1)
        {
            e1.printStackTrace();
        }
    }
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    服务端 frame = new 服务端();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public 服务端() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("服务端");
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        JTextArea textArea = new JTextArea();
        BtextArea =textArea;
        textArea.setBounds(0, 15, 300, 137);
        //contentPane.add(textArea);
        JScrollPane jsp = new JScrollPane(textArea); //在文本框上添加滚动条
        jsp.setBounds(0, 15, 350, 100);
        //默认的设置是超过文本框才会显示滚动条,以下设置让滚动条一直显示
         jsp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         
        contentPane.add(jsp);
        textField = new JTextField();
        textField.setBounds(0, 167, 287, 62);
        contentPane.add(textField);
        textField.setColumns(10);
        
        JButton button = new JButton("\\u53D1\\u9001");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                send();
            }
            });
        button.setBounds(302, 200, 123, 29);
        contentPane.add(button);
        
        JButton button_1 = new JButton("\\u5F00\\u59CB\\u670D\\u52A1");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                connect();        
            }
        });
        button_1.setBounds(302, 147, 123, 29);
        contentPane.add(button_1);
        thread=new Thread(this);
        //thread.run();
    }
}

 

客户端:

package 实验五聊天;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;

import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class 客户端 extends JFrame implements  Runnable{

    private JPanel contentPane;
    private JTextField textField;
    private JButton button;
    private  static JTextArea BtextArea;
    public static ServerSocket serverSocket=null;
    public static Socket clientSocket=null;
    public  Socket client=null;
    public DataOutputStream out=null;
    public static DataInputStream in=null;
    private Thread thread;
    public void run()
        {
            try
            {
                while(true)
                {        
                    
                    if(in!=null)
                        {
                            String tmp=in.readUTF();
                            BtextArea.append("\\n服务端:\\n"+tmp);
                        }
                }
            
            }catch (Exception e) {
                e.printStackTrace();
            }    
        }
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    客户端 frame = new 客户端();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    //frame.setTitle("客户端");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public void  connect()
    {
            InetAddress localIP=null;
            try {
                if(client==null)
                {
                    localIP = InetAddress.getLocalHost();
                    client=new Socket(localIP,8000);
                    out=new DataOutputStream(client.getOutputStream());
                    in=new DataInputStream(client.getInputStream());
                    if(!(thread.isAlive()))
                    {
                        thread=new Thread(this);
                    }
                    thread.start();
                }
            } catch (UnknownHostException   e2) {
                // TODO 自动生成的 catch 块
                e2.printStackTrace();
            }
            catch(IOException e2)
            {
                e2.printStackTrace();
            }
    }
    /**
     * Create the frame.
     */
    public 客户端() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        setTitle("客户端");
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        JTextArea textArea = new JTextArea();
        textArea.setBounds(0, 0, 299, 132);
        BtextArea=textArea;
        JScrollPane jsp = new JScrollPane(textArea); //在文本框上添加滚动条
        jsp.setBounds(0, 15, 350, 100);
        //默认的设置是超过文本框才会显示滚动条,以下设置让滚动条一直显示
         jsp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         
        contentPane.add(jsp);
        
        textField = new JTextField();
        textField.setBounds(10, 127, 257, 102);
        contentPane.add(textField);
        textField.setColumns(10);
        
        button = new JButton("\\u53D1\\u9001");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                 String tmp=textField.getText();
                 textField.setText("");
                 BtextArea.append("\\n客户端:"+tmp);
                 try
                 {
                     out.writeUTF(tmp);
                 }
                 catch(Exception e1)
                 {
                     e1.printStackTrace();
                 }
            }
        });
        button.setBounds(282, 185, 123, 29);
        contentPane.add(button);
        
        JButton button_1 = new JButton("\\u8FDE\\u63A5");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                connect();
            }
        });
        button_1.setBounds(282, 130, 123, 29);
        contentPane.add(button_1);
        thread=new Thread(this);
    }
}

实现效果:

 

以上是关于JAVA客户端与服务端Socket通信问题的主要内容,如果未能解决你的问题,请参考以下文章

Java中Socket 实现最简单的客户端与服务端通信

java Socket通信,客户端与服务端相互发消息

linux用java socket与c的socket通信乱码问题

Java 网络编程

java 界面编程用socket实现服务端与客户端的循环通信。

java服务端与c++客户端的socket通信问题