Socket通信

来源:互联网 发布:icm20608中文数据手册 编辑:程序博客网 时间:2024/04/28 16:35
Socket编程原理:从连接的建立到连接的结束,每个Socket应用都大致包含以下几个基本步骤: 1.服务器端Socket绑定于特定的端口,服务器侦听socket等待连接请求; 2.客户端向服务器提交连接请求; 3.服务器接受连接,产生一个新的socket,绑定到另一个端口,由此socket来处理和客户端的交互; 4.服务器端和客户端通过各自的socket进行通讯; 5.关闭输入输出流和socket 。 Java Socket实现: 1.ServerSocket serverSocket=new ServerSocket(1068); Socket echoServerSocket=serverSocket.accept(); 注意: Socket和ServerSocket位于java.net包中,需要import进来。 1024以下的端口是保留端口,不能使用。允许使用的范围1024-65535 accept方法用于产生阻塞,服务器一直等待客户端的连接,直到接受到一个连接,代码才继续往下执行。 2.Socket clientSocket=new Socket(ipStr,port); 注意: ipStr指明服务器端位置,可以是ip地址,也可以是主机名。 Port指明服务器端socket侦听的端口。客户端不需要指明它自己的端口号,通常是临时动态地分配一个1024以上的端口。 3.Socket echoServerSocket=serverSocket.accept(); 注意:服务器端接受客户端的连接后,在服务端自动再创建一个临时的socket交由它来与客户端的socket进行通讯。 4.BufferedReader in= new BufferedReader(new InputStreamReader(echoServerSocket.getInputStream()) PrintWriter out = new PrintWriter(echoServerSocket.getOutputStream(),true); String strFromClient; while((strFromClient = in.readLine()) != null) { out.println("result is :"+ strFromClient); } 注意: echoServerSocket.getInputStream()从socket获得输入流 echoServerSocket.getOutputStream()从socket获得输出流 注意PrintWriter类构造方法第二个参数的意思。 in.readLine在客户端还未发送信息时,一直返回null 以下为我做的一个简单的例子,功能还不是很完善,还有待改进。 //Server.java package socket; import java.net.*; import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; class WinClosing extends WindowAdapter{ //关闭窗口 public void windowClosing(WindowEvent e){ System.exit(0); } } class Server implements Runnable, ActionListener{ JLabel port,acceptance,sends; JButton jianting,send; JTextField portContent,acceptContent,sendsContent; JFrame f; String sendMesg; Socket socket = null; InputStream in; OutputStream out; ServerSocket serverSocket; boolean isReady = false; public Server(){ f = new JFrame("简单的聊天程序(Server端)"); Container contentPane = f.getContentPane(); contentPane.setLayout(new GridLayout(4,1)); JPanel p1 = new JPanel(new FlowLayout()); JPanel p2 = new JPanel(new GridLayout(2,1)); JPanel p3 = new JPanel(new GridLayout(2,1)); JPanel p4 = new JPanel(new FlowLayout(FlowLayout.RIGHT)); port=new JLabel("端口号"); acceptance=new JLabel(" 接收到的信息"); sends=new JLabel(" 要发送的信息"); jianting=new JButton("监听"); send=new JButton("发送"); portContent=new JTextField(" ",5); acceptContent=new JTextField(" ",20); sendsContent=new JTextField(" ",20); p1.add(port); p1.add(portContent); p1.add(jianting); p2.add(acceptance); p2.add(acceptContent); p3.add(sends); p3.add(sendsContent); p4.add(send); jianting.addActionListener(this); send.addActionListener(this); portContent.addActionListener(this); sendsContent.addActionListener(this); contentPane.add(p1); contentPane.add(p2); contentPane.add(p3); contentPane.add(p4); f.setSize(300,250); f.setVisible(true); f.addWindowListener(new WinClosing()); //f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { if(e.getSource() == jianting) { try{ int port = Integer.parseInt(portContent.getText().trim()); serverSocket = new ServerSocket(port); socket = serverSocket.accept(); System.out.println("conn succ!"); }catch(Exception e1) { System.out.println("Server failed!"); } isReady = true; new Thread(this).start(); } if (e.getSource() == send) { sendMesg = sendsContent.getText().trim(); if (isReady) { if (sendMesg == "" || sendMesg == null) { sendsContent.setText("sends error"); }else{ try{ out = socket.getOutputStream(); byte[] b = sendMesg.getBytes(); System.out.println("sendsContent:" + b); out.write(b); }catch (Exception ex) { System.out.println("IOException"); } } } } } public void run(){ byte[] recv = new byte[60]; try{ do{ in = socket.getInputStream(); in.read(recv); acceptContent.setText(new String(recv)); }while(recv != null); }catch (IOException e) { System.out.println("I/O failed!"); } } public static void main(String[] args){ new Server(); } } //Client.java package socket; import java.net.*; import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Client implements Runnable, ActionListener{ JFrame f; JLabel addr,port,acceptance,sends; JButton conn,send; JTextField addrContent,portContent,acceptContent,sendsContent; InputStream in; OutputStream out; Socket s; boolean isConnected = false; public Client(){ //构造函数:实现客户端界面 f = new JFrame("简单的聊天程序(Client端)"); Container contentPane = f.getContentPane(); contentPane.setLayout(new GridLayout(4,1)); JPanel p1 = new JPanel(new FlowLayout()); JPanel p2 = new JPanel(new GridLayout(2,1)); JPanel p3 = new JPanel(new GridLayout(2,1)); JPanel p4 = new JPanel(new FlowLayout(FlowLayout.RIGHT)); addr=new JLabel("地址"); port=new JLabel("端口号"); acceptance=new JLabel(" 接收到的信息"); sends=new JLabel(" 要发送的信息"); conn=new JButton("连接"); send=new JButton("发送"); addrContent=new JTextField(" ",5); portContent=new JTextField(" ",5); acceptContent=new JTextField(" ",20); sendsContent=new JTextField(" ",20); p1.add(addr); p1.add(addrContent); p1.add(port); p1.add(portContent); p1.add(conn); p2.add(acceptance); p2.add(acceptContent); p3.add(sends); p3.add(sendsContent); p4.add(send); conn.addActionListener(this); send.addActionListener(this); addrContent.addActionListener(this); portContent.addActionListener(this); sendsContent.addActionListener(this); contentPane.add(p1); contentPane.add(p2); contentPane.add(p3); contentPane.add(p4); //f.pack(); f.setSize(300,250); f.setVisible(true); /*f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } });*/ f.addWindowListener(new WinClosing());//关闭窗口 } public void actionPerformed(ActionEvent e) { if(e.getSource() == conn){ String ip = addrContent.getText().trim(); int port = Integer.parseInt(portContent.getText().trim()); try { InetAddress address = InetAddress.getByName(ip); s = new Socket(address, port); //s= new Socket("localhost", port); in = s.getInputStream(); out = s.getOutputStream(); isConnected = true; System.out.println("connection successful!"); new Thread(this).start(); } catch (Exception ex) { ex.printStackTrace(); } }else{ //if(isConnected){ if((e.getSource() == send) && (isConnected ==true)){ String sendMesg = sendsContent.getText().trim(); try{ out = s.getOutputStream(); //向对方发送消息 byte[] b = sendMesg.getBytes(); out.write(b); } catch(IOException e1){ e1.printStackTrace(); } } } } public void run(){ byte[] recv = new byte[60]; try{ do{ in = s.getInputStream(); in.read(recv); System.out.println("receive:"+recv); acceptContent.setText(new String(recv)); }while(recv!=null); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args){ new Client(); } }
原创粉丝点击