java socket编程

 

TcpServer

Server端所要做的事情主要是建立一个通信的端点,然后等待客户端发送的请求。典型的处理步骤如下:

1. 构建一个ServerSocket实例,指定本地的端口。这个socket就是用来监听指定端口的连接请求的。

2. 调用socket的accept()方法来获得下面客户端的连接请求。通过accept()方法返回的socket实例,建立了一个和客户端的新连接。

3.通过这个返回的socket实例获取InputStream和OutputStream,可以通过这两个stream来分别读和写数据。

4.结束的时候调用socket实例的close()方法关闭socket连接。

java socket编程
package socket;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
     
       public static void main(String args[]) throws IOException {
          //为了简单起见,所有的异常信息都往外抛
          int port = 8899;
          //定义一个ServerSocket监听在端口8899上
          ServerSocket server = new ServerSocket(port);
          //server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
          Socket socket = server.accept();
          //跟客户端建立好连接之后,我们就可以获取socket的InputStream,并从中读取客户端发过来的信息了。
          Reader reader = new InputStreamReader(socket.getInputStream());
          char chars[] = new char[64];
          int len;
          StringBuilder sb = new StringBuilder();
          while ((len=reader.read(chars)) != -1) {
             sb.append(new String(chars, 0, len));
          }
          System.out.println("from client: " + sb);
          reader.close();
          socket.close();
          server.close();
       }
       
    }
java socket编程

 

TcpClient端

客户端的请求过程稍微有点不一样:

1.构建Socket实例,通过指定的远程服务器地址和端口来建立连接。

2.通过Socket实例包含的InputStream和OutputStream来进行数据的读写。

3.操作结束后调用socket实例的close方法,关闭。

java socket编程
package socket;

import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;

public class Client {
     
       public static void main(String args[]) throws Exception {
          //为了简单起见,所有的异常都直接往外抛
          String host = "10.21.23.144";  //要连接的服务端IP地址
          int port = 8899;   //要连接的服务端对应的监听端口
          //与服务端建立连接
          Socket client = new Socket(host, port);
          //建立连接后就可以往服务端写数据了
          Writer writer = new OutputStreamWriter(client.getOutputStream());
         
          writer.write("Hello mynona Server.");
          writer.flush();//写完后要记得flush
          writer.close();
          client.close();
       }
       
    }
java socket编程

 

Udp:

server端

因为UDP协议不需要建立连接,它的过程如下:

1. 构造DatagramSocket实例,指定本地端口。

2. 通过DatagramSocket实例的receive方法接收DatagramPacket.DatagramPacket中间就包含了通信的内容。

3. 通过DatagramSocket的send和receive方法来收和发DatagramPacket.

 

java socket编程
package Udp2;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class UDPServer {
    public static void main(String args[]) throws Exception
    {
        //监听9876端口
       DatagramSocket serverSocket = new DatagramSocket(9876);
          byte[] receiveData = new byte[1024];
          byte[] sendData = new byte[1024];
          while(true)
             {
                //构造数据包接收数据
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                //接收数据
                serverSocket.receive(receivePacket);
                //解析数据
                String sentence = new String( receivePacket.getData());
                System.out.println("RECEIVED: " + sentence);
              
                InetAddress IPAddress = receivePacket.getAddress();
                int port = receivePacket.getPort();
                String capitalizedSentence = sentence.toUpperCase();
                sendData = capitalizedSentence.getBytes();
                
                //构造发送数据包发送数据
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
                serverSocket.send(sendPacket);
             }
    }
}
java socket编程

 

UdpClient:

1. 构造DatagramSocket实例。

2.通过DatagramSocket实例的send和receive方法发送DatagramPacket报文。

3.结束后,调用DatagramSocket的close方法关闭。

java socket编程
package Udp2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {

     public static void main(String args[]) throws Exception
       {
          BufferedReader inFromUser =
             new BufferedReader(new InputStreamReader(System.in));
          DatagramSocket clientSocket = new DatagramSocket();
          InetAddress IPAddress = InetAddress.getByName("localhost");
          System.out.println("IPAddress:" + IPAddress);
          byte[] sendData = new byte[1024];
          byte[] receiveData = new byte[1024];
          String sentence = inFromUser.readLine();
          sendData = sentence.getBytes();
          
          //发送数据
          DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
          clientSocket.send(sendPacket);
          
          //接收数据
          DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
          clientSocket.receive(receivePacket);
          String modifiedSentence = new String(receivePacket.getData());
          System.out.println("FROM SERVER:" + modifiedSentence);
          clientSocket.close();
       }
}
java socket编程

 

参考来源:http://shmilyaw-hotmail-com.iteye.com/blog/1556187

http://haohaoxuexi.iteye.com/blog/1979837

java socket编程,布布扣,bubuko.com

java socket编程

上一篇:TcaplusDB小知识之TcaplusDB架构简介


下一篇:如何用python查询mysql乱码问题?