java socket推送

客户端代码:客户端没调用一次就关掉,但是服务让其一直等待

importorg.springframework.stereotype.Component;

importjava.io.BufferedReader;

importjava.io.IOException;

importjava.io.InputStreamReader;

importjava.io.OutputStream;

importjava.net.Socket;

@Component

public classMyClient {

staticSocketserver;

privateStringstring;

public staticSocketgetServer() {

returnserver;

}

public static voidsetServer(Socket server) {

MyClient.server= server;

}

public voidMyClient(String string){

this.string= string;

}

public voidpushMessage(String string){

try{

server=newSocket("127.0.0.1",5265);

OutputStream out =server.getOutputStream();

BufferedReader in =newBufferedReader(newInputStreamReader(

server.getInputStream()));

try{

System.out.println("=================="+ string);

out.write(string.getBytes());

out.flush();

}catch(IOException e) {

e.printStackTrace();

}

server.close();

}catch(Exception e){

}

}

}

服务端代码:

import java.io.IOException;

import java.io.InputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class MyServer extends Thread {

private Socket client;

public MyServer(Socket c) {

this.client = c;

}

public void run() {

InputStream in = null;

try {

in = client.getInputStream();

} catch (IOException e1) {

e1.printStackTrace();

}

try {

byte[] bytes = new byte[in.available()];

in.read(bytes);

String res = new String(bytes);

System.out.println("line:" + res);

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) throws IOException {

ServerSocket server = new ServerSocket(5265);

while (true) {

MyServer mc = new MyServer(server.accept());

mc.start();

}

}

}

你可能感兴趣的:(java socket推送)