基于JAVA发送TCP请求
示例
java实现TCP请求,主要是通过Socker。
客户端
package TCP;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class TCPClient {
public static void main(String[] args) {
TCPClient client = new TCPClient();
SimpleDateFormat format = new SimpleDateFormat("hh-MM-ss");
Scanner scanner = new Scanner(System.in);
while(true){
String msg = scanner.nextLine();
if("#".equals(msg))
break;
//打印响应的数据
System.out.println("send time : " + format.format(new Date()));
System.out.println(client.sendAndReceive(TCPService.SERVICE_IP,TCPService.SERVICE_PORT,msg));
System.out.println("receive time : " + format.format(new Date()));
}
}
private String sendAndReceive(String ip, int port, String msg){
//这里比较重要,需要给请求信息添加终止符,否则服务端会在解析数据时,一直等待
msg = msg+TCPService.END_CHAR;
StringBuilder receiveMsg = new StringBuilder();
//开启一个链接,需要指定地址和端口
try (Socket client = new Socket(ip, port)){
//向输出流中写入数据,传向服务端
OutputStream out = client.getOutputStream();
out.write(msg.getBytes());
//从输入流中解析数据,输入流来自服务端的响应
InputStream in = client.getInputStream();
for (int c = in.read(); c != TCPService.END_CHAR; c = in.read()) {
if(c==-1)
break;
receiveMsg.append((char)c);
}
}catch (Exception e){
e.printStackTrace();
}
return receiveMsg.toString();
}
}
服务端1:
package TCP;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPService {
public static final String SERVICE_IP = "127.0.0.1";
public static final int SERVICE_PORT = 10101;
public static final char END_CHAR = '#';
public static void main(String[] args) {
TCPService service = new TCPService();
//启动服务端
service.startService(SERVICE_IP,SERVICE_PORT);
}
private void startService(String serverIP, int serverPort){
try {
//封装服务端地址
InetAddress serverAddress = InetAddress.getByName(serverIP);
//建立服务端
try(ServerSocket service = new ServerSocket(serverPort, 10, serverAddress)){
while (true) {
StringBuilder receiveMsg = new StringBuilder();
//接受一个连接,该方法会阻塞程序,直到一个链接到来
try(Socket connect = service.accept()){
//获得输入流
InputStream in = connect.getInputStream();
//解析输入流,遇到终止符结束,该输入流来自客户端
for (int c = in.read(); c != END_CHAR; c = in.read()) {
if(c ==-1)
break;
receiveMsg.append((char)c);
}
//组建响应信息
String response = "Hello world " + receiveMsg.toString() + END_CHAR;
//获取输入流,并通过向输出流写数据的方式发送响应
OutputStream out = connect.getOutputStream();
out.write(response.getBytes());
}catch (Exception e){
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
服务端2:
package TCP;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TCPService1 {
public static final String SERVICE_IP = "127.0.0.1";
public static final int SERVICE_PORT = 10101;
public static final char END_CHAR = '#';
public static void main(String[] args) {
TCPService1 service1 = new TCPService1();
service1.startService();
}
private void startService(){
try {
InetAddress address = InetAddress.getByName(SERVICE_IP);
Socket connect = null;
ExecutorService pool = Executors.newFixedThreadPool(5);
try (ServerSocket service = new ServerSocket(SERVICE_PORT,5,address)){
while(true){
connect = service.accept();
//创建一个任务
ServiceTask serviceTask = new ServiceTask(connect);
//放入线程池等待运行
pool.execute(serviceTask);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(connect!=null)
connect.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
class ServiceTask implements Runnable{
private Socket socket;
ServiceTask(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try {
StringBuilder receiveMsg = new StringBuilder();
InputStream in = socket.getInputStream();
for (int c = in.read(); c != END_CHAR; c = in.read()) {
if(c ==-1)
break;
receiveMsg.append((char)c);
}
String response = "Hello world " + receiveMsg.toString() + END_CHAR;
Thread.currentThread().sleep(5000);
OutputStream out = socket.getOutputStream();
out.write(response.getBytes());
}catch (Exception e){
e.printStackTrace();
}finally {
if(socket!=null)
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}