JAVA的socket编程

1、网络编程的三类socket

SOCK_STREAM:TCP,一对一字节流通信,双向通信
SOCK_DGRAM:UDP,报文服务,双向通信
SOCK_RAW:java不支持

2、Socket服务器

(1)端口port范围0-65525,port = 0时监听所有空闲端口。
(2)服务器示例代码,添加异常处理

import java.io.*
import java.net.*
public class ServerView{
  public static void main() throws IOException{
    int port = 9779;
    ServerSocket ss = null;
    Socket s = null;
    BufferedReader br = null;
    PrintWriter pw = null;
    try{
      ss = new ServerSocket(port);
      s = ss.accept(); //进程阻塞直到接收到客户端请求

      // 调用Socket对象的getOutputStream()方法得到输入流
      br = new BufferedReader(new InputStreamReader(s.getInputStream()));
      // 调用Socket对象的getOutputStream()方法得到输出流
      pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

      // 读取从客户端传过来的数据并加上"echo: ",发回给客户端
      String str = "";
      while((str = br.readLine()) != null) {
        pw.print("echo:" + str); // 发回
        pw.flush(); 
      }
    } catch(IOException e) { // 捕获异常输出
      System.out.println(e);
    } finally {
      // 关闭连接
      br.close();
      pw.close();
      s.close();
      ss.close();
    }
  }
}

3、Socket客户端

(1)建立连接

try{
  String host = "localhost"; // ip地址或主机名称
  String port = 9779;
  Socket clientSocket = new Socket(host, port);
} catch (UnknowHostException e) { 
  // 无法确定IP地址所代表的主机
  System.out.println("主机不存在");
} catch (IOException e) {
  // 创建套接字时发送IO异常
  System.out.println("服务不存在或忙");
}

(2)与服务器交互

与服务器交互需要从上一步建立的Socket对象中获取数据输入流和数据输出流。我们从数据输出流中获取服务器进程返回的信息,将我们的请求写入数据输入流中

// 数据输入流:获取并处理来自服务器的信息
try {
  BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  String message = "";
  while( message = input.readLine() != null ) {
    ... // 按行处理来自服务器的消息
  }
} catch (IOException e) {
  System.out.println("数据读取出错:" + e.getMessage());
}


// 数据输出流:向服务器发送信息
try {
  PrintWriter output = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
  String message = "";
  ... // 用户输入数据到message
  
  // 发送信息
  output.println(message);
  output.flush();
} catch(IOException e) {
  System.out.println("数据写入错误:" + e.getMessage());
}

(3)关闭Socket服务

关闭输入输出流和套接字

try {
  output.close();
  input.close();
  socket.close();
} catch(IOException e) {
  System.out.println("关闭出错:" + e.getMessage());
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 网络编程 一.楔子 你现在已经学会了写python代码,假如你写了两个python文件a.py和b.py,分别去运...
    go以恒阅读 6,399评论 0 6
  • 大纲 一.Socket简介 二.BSD Socket编程准备 1.地址 2.端口 3.网络字节序 4.半相关与全相...
    VD2012阅读 7,204评论 0 5
  • 说明 本文 翻译自 realpython 网站上的文章教程 Socket Programming in Pytho...
    keelii阅读 6,623评论 0 16
  • 对TCP/IP、UDP、Socket编程这些词你不会很陌生吧?随着网络技术的发展,这些词充斥着我们的耳朵。那么我想...
    yuantao123434阅读 10,772评论 1 97
  • Java Socket编程 对于Java Socket编程而言,有两个概念,一个是ServerSocket,一个是...
    天空下天的月亮阅读 6,195评论 10 41