1、所谓socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过"套接字"向网络发出请求或者应答网络请求。
操作java socket时用到的最多的三个方法为:
accept():主要用于服务器端产生“阻塞”,等待客户端的链接请求,并且返回一个客户端的Socket实例;
getInputStream():方法主要用来获得网络连接输入,同时返回一个InputStream对象实例;
getOutputStream():方法和上面的getInputStream相反。
2、一般要建立Java的Socket连接,应首先明确服务器端和客户端,服务器端使用ServerSocket监听指定的端口,使用accept等待客户端请求,链接链接,开始会话、完成会话后,关闭链接。(注意,一般socket的关闭都应该是服务器端来进行的,后面说);客户端使用Socket对网络中的某个服务器的某个端口发出链接请求,连接成功,开始会话,会话完成,Socket关闭。
2、示例代码:
服务器端:
package com.icer.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Server
*
* @author Icer
*
*/
public class Server {
private ServerSocket ss;
private Socket s;
private BufferedReader br;
private PrintWriter pw;
public Server() {
try {
ss = new ServerSocket(10000);
System.out.println("Server is starting...");
s = ss.accept();
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(),true);
String line = br.readLine();
System.out.println(line);
pw.println("your word is:" + line);
//pw.println("helloworld");
br.close();
pw.close();
} catch (IOException ie) {
ie.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
new Server();
}
}
客户端:
package com.icer.client;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Client
* @author Icer
*
*/
public class Client {
private Socket s;
private BufferedReader br;
//private BufferedReader line;
private PrintWriter pw;
private String line = "";
public Client() {
try{
s = new Socket("127.0.0.1",10000);
pw = new PrintWriter(s.getOutputStream(),true);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw.println("hello");
line = br.readLine();
System.out.println(line);
br.close();
pw.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
new Client();
}
}