1. 服务器端

package socket;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;
import java.net.*;

class SocketServer extends JFrame
  implements ActionListener {

JButton button;
   JLabel label = new JLabel("Text received over socket:");
   JPanel panel;
   JTextArea textArea = new JTextArea();
   ServerSocket server = null;
   Socket client = null;
   BufferedReader in = null;
   PrintWriter out = null;
   String line;

SocketServer(){ //Begin Constructor
     button = new JButton("Click Me");
     button.addActionListener(this);

panel = new JPanel();
     panel.setLayout(new BorderLayout());
     panel.setBackground(Color.white);
     getContentPane().add(panel);
     panel.add("North", label);
     panel.add("Center", textArea);
     panel.add("South", button);

} //End Constructor

public void actionPerformed(ActionEvent event) {
     Object source = event.getSource();

if(source == button){
         textArea.setText(line);
     }
  }

public void listenSocket(){

try{
      server = new ServerSocket(4444); 
    
} catch (IOException e) {
      System.out.println("Could not listen on port 4444");
      System.exit(-1);
    }

try{
      client = server.accept();
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }

try{
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }
 
    while(true){
      try{
        line = in.readLine();
//Send data back to client
        out.println(line);
      } catch (IOException e) {
        System.out.println("Read failed");
        System.exit(-1);
      }
    }
  }

protected void finalize(){
//Clean up 
     try{
        in.close();
        out.close();
        server.close();
    } catch (IOException e) {
        System.out.println("Could not close.");
        System.exit(-1);
    }
  }

public static void main(String[] args){
        SocketServer frame = new SocketServer();
 frame.setTitle("Server Program");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };
        frame.addWindowListener(l);
        frame.pack();
        frame.setVisible(true);
 frame.listenSocket();
  }
}

###########

客户端

package socket;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;
import java.net.*;
class SocketClient extends JFrame
   implements ActionListener {

/**
  * 
  */
 private static final long serialVersionUID = 1L;
JLabel text, clicked;
   JButton button;
   JPanel panel;
   JTextField textField;
   Socket socket = null;
   PrintWriter out = null;
   BufferedReader in = null;

SocketClient(){ //Begin Constructor
     text = new JLabel("Text to send over socket:");
     textField = new JTextField(20);
     button = new JButton("Click Me");
     button.addActionListener(this);

panel = new JPanel();
     panel.setLayout(new BorderLayout());
     panel.setBackground(Color.white);
     getContentPane().add(panel);
     panel.add("North", text);
     panel.add("Center", textField);
     panel.add("South", button);
   } //End Constructor

public void actionPerformed(ActionEvent event){
     Object source = event.getSource();

if(source == button){
//Send data over socket
          String text = textField.getText();
          out.println(text);
   textField.setText(new String(""));
//Receive text from server
       try{
   String line = in.readLine();
          System.out.println("Text received :" + line);
       } catch (IOException e){
  System.out.println("Read failed");
         System.exit(1);
       }
     }
  }
  
  public void listenSocket(){
//Create socket connection
     try{
       socket = new Socket("127.0.0.1", 4444);
       out = new PrintWriter(socket.getOutputStream(), true);
       in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     } catch (UnknownHostException e) {
       System.out.println("Unknown host: kq6py.eng");
       System.exit(1);
     } catch  (IOException e) {
       System.out.println("No I/O");
       System.exit(1);
     }
  }

public static void main(String[] args){
        SocketClient frame = new SocketClient();
 frame.setTitle("Client Program");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };

frame.addWindowListener(l);
        frame.pack();
        frame.setVisible(true);
 frame.listenSocket();
  }
}

本文转自 randy_shandong 51CTO博客,原文链接:http://blog.51cto.com/dba10g/707095,如需转载请自行联系原作者

Lesson 1:单线程 Socket Communications(一)相关推荐

  1. python多线程ftp服务器_一小时学会用Python Socket 开发可并发的FTP服务器!!

    socket是什么 什么是socket所谓socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄.应用程序通常通过"套接字"向网络发出请求 ...

  2. Code Project精彩系列(转)

    Applications Crafting a C# forms Editor From scratch http://www.codeproject.com/csharp/SharpFormEdit ...

  3. codeproject资源集合贴

    Applications Crafting a C# forms Editor From scratch http://www.codeproject.com/csharp/SharpFormEdit ...

  4. Code Project精彩系列

    Applications Crafting a C# forms Editor From scratch http://www.codeproject.com/csharp/SharpFormEdit ...

  5. Code Project精彩系列二

    Applications Crafting a C# forms Editor From scratch http://www.codeproject.com/csharp/SharpFormEdit ...

  6. Code Project

    Applications Crafting a C# forms Editor From scratch http://www.codeproject.com/csharp/SharpFormEdit ...

  7. Code Project精彩系列(2)

    Windows Forms Fireball Resourcer 把各种资源嵌入应用程序资源 Window Hiding with C# 隐藏窗体, 似乎是其它运行的窗体 J Proper Threa ...

  8. Mina代码跟踪(1)

    为什么80%的码农都做不了架构师?>>>    1  NioSocketAcceptor类关系图 1.1 NioSocketAcceptor acceptor = new NioSo ...

  9. linux来源usb驱动在哪下载,Linux USB驱动程序基础

    非常好的linux驱动入门,介绍详尽 Linux USB驱动程序基础 来源: ChinaUnix博客日期:2008.04.10 23:55(共有条评论) 我要评论 ( Linux USB Driver ...

最新文章

  1. Office 2003出现发送错误报告怎么办
  2. oddo docker 安装
  3. Ant在MyEclipse中的配置总结
  4. oracle 11g如何完全卸载
  5. 推荐!计算机视觉最适合入门的 8 本教程,算法与实战兼备
  6. [渝粤教育] 西南科技大学 工程测量 在线考试复习资料
  7. CentOS Linux 7.9 (2009) 发布
  8. 论文赏析[NAACL16]RNN文法
  9. 总结oninput、onchange与onpropertychange事件的使用方法和差别
  10. 微软建议用户关闭Win7桌面小工具和侧边栏
  11. SQLServer安装Northwind数据库
  12. 前端工程师的前途与价值体现
  13. 沁恒MCU串口使用指南
  14. Android 中Goolgle 相关服务的移植[转]
  15. 技术流 | 知乎高赞,最值得推荐的电影都有哪些?
  16. 合影效果java_〖摄影技术〗6个姿势,教你拍好合影
  17. selenium操作firefox
  18. 励志长篇小说《周兴和》书连载之二饥饿寒冷童年
  19. 【codecs】视频显示分辨率格式分析
  20. 学习JBPM 工作流引擎 API方法(二)

热门文章

  1. GeneralList-广义表
  2. ORA-01172,ORA-01151
  3. Leetcode 583.两个字符串的删除操作
  4. vue 给url 中文参数 添加编码解码
  5. spring手动回滚
  6. 微信公众号开发 [03] 结合UEditor实现图文消息群发功能
  7. 【COGS1752】 BOI2007—摩基亚Mokia
  8. 【转】蓝牙物理链路类型:SCO和ACL链路
  9. 增加 addDataScheme(file) 才能收到SD卡插拔事件的原因分析 -- 浅析android事件过滤策略...
  10. iPhone开发【一】从HelloWorld開始