Java Socket 编程,分为Socket 和ServerSocket两个类,其中Client 通过构造Socket 实例,向Server 端的ServerSocket发起请求。 ServerSocket 在接受到来自Client 的请求后,构建一个Socket,并将响应内容通过这个Socket实例返回。
Socket编程可以使用各种不同的传输层协议,本例以TCP协议为例,展示这个交互过程。
Client:
package com.mahoutchina.java.socket.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class TCPEchoClient {
/**
* @param args
*/
public static void main(String[] args) {
if (args.length < 2 || (args.length > 3)) {
throw new IllegalArgumentException(
"Parameter(s):<Server> <Word>[<Port>]");
}
String server = args[0];// server name or IP address
// Convert argument string to bytes using the default character encoding
String sendData=args[1];
System.out.println("Data to sent:"+ sendData);
byte[] data = sendData.getBytes();
int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;
System.out.println("Server port:"+servPort);
// create socket that is connected to server on specified port
Socket socket = null;
try {
socket = new Socket(server, servPort);
System.out.println("Connected to server ... sending echo string");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(data);
// receive
int totalBytesRcvd = 0;// total bytes received so far
int bytesRcvd;// Bytes received in last read
while (totalBytesRcvd < data.length) {
bytesRcvd = in.read(data, totalBytesRcvd, data.length
- totalBytesRcvd);
if (bytesRcvd == -1) {
throw new SocketException("Connection closed prematurely");
}
totalBytesRcvd += bytesRcvd;
}
System.out.println("Received:" + new String(data));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务器端:
package com.mahoutchina.java.socket.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
public class TCPEchoServer {
//Size of receive buffer
private static final int BUFSIZE=32;
/**
* @param args
*/
public static void main(String[] args) {
//Test for correct # of args
if(args.length!=1){
throw new IllegalArgumentException("Parameter(s):<Port>");
}
int servPort = Integer.parseInt(args[0]);
//Create a server socket to accept client connection request
ServerSocket servSocket =null;
int recvMsgSize=0;
byte[] receivBuf=new byte[BUFSIZE];
try {
servSocket=new ServerSocket(servPort);
while(true){
Socket clientSocket=servSocket.accept();
SocketAddress clientAddress = clientSocket.getRemoteSocketAddress();
System.out.println("Handling client at "+ clientAddress);
InputStream in =clientSocket.getInputStream();
OutputStream out= clientSocket.getOutputStream();
//receive until client close connection,indicate by -l return
while((recvMsgSize=in.read(receivBuf))!=-1){
String receivedData=new String(receivBuf.toString());
System.out.println(receivedData);
out.write(receivBuf, 0, recvMsgSize);
}
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行:
先运行server client,配置的参数为9999
Handling client at /192.168.1.117:50128
helloEcho
运行client,参数:localhost helloEcho 999
Data to sent:helloEcho
Server port:9999
Connected to server ... sending echo string
Received:helloEcho