Socket通常也称做”套接字“,用于描述IP地址和端口,废话不多说,它就是网络通信过程中端点的抽象表示。值得一提的是,Java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用起来很方便!
下面将首先创建一个SocketServer的类作为服务端如下,该服务端实现了多线程机制,可以在特定端口处监听多个客户请求,一旦有客户请求,Server总是会创建一个服务纯种来服务新来的客户,而自己继续监听。程序中accept()是一个阻塞函数,所谓阻塞性方法就是说该方法被调用后将等待客户的请求,直到有一个客户启动并请求连接到相同的端口,然后accept()返回一个对应于客户的Socket。这时,客户方和服务方都建立了用于通信的Socket,接下来就是由各个Socket分别打开各自的输入、输出流。
SocketServer类,服务器实现:
import java.io.*;
import java.net.*;
class SocketServer {
ServerSocket sever;
public SocketServer(int port){
try{
sever = new ServerSocket(port);
}catch(IOException e){
e.printStackTrace();
}
}
public void beginListen(){
while(true){
try{
final Socket socket = sever.accept();
new Thread(new Runnable(){
public void run(){
BufferedReader in;
try{
in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
PrintWriter out = new PrintWriter(socket.getOutputStream());
while (!socket.isClosed()){
String str;
str = in.readLine();
out.println("Hello!world!! " + str);
out.flush();
if (str == null || str.equals("end"))
break;
System.out.println(str);
}
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}).start();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
public class server
{
public static void main(String[] args)
{
System.out.println("server startup...");
SocketServer sockServ = new SocketServer(8083);
sockServ.beginListen();
System.out.println("server endup...");
}
}
SocketClient类,客户端实现:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
class SocketClient
{
static Socket client;
public SocketClient(String site, int port){
try
{
client = new Socket(site,port);
System.out.println("Client is created! site:"+site+" port:"+port);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public String sendMsg(String msg){
try{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
out.println(msg);
out.flush();
return in.readLine();
}catch(IOException e){
e.printStackTrace();
}
return "";
}
public void closeSocket(){
try{
client.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
public class client
{
public static void main(String[] args)
{
System.out.println("client startup...");
SocketClient cliSocket = new SocketClient("10.1.36.73",8083);
//SocketClient cliSocket = new SocketClient("127.0.0.1",8083);
System.out.println(cliSocket.sendMsg("test data1..."));
cliSocket.closeSocket();
}
}
若要在Android中进行编程需要在AndroidManifest.xml文件中开通响应属性,如下:
接下来就是来测试Socket通信了!
1、启动服务器端代码,等待接收客户端的数据
2、启动客户端代码发送数据到服务器端
以上代码用javac、java运行即可测试。