美文网首页
java socket推送

java socket推送

作者: Easy的幸福 | 来源:发表于2017-09-14 16:07 被阅读0次

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

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推送

      本文链接:https://www.haomeiwen.com/subject/jkpdsxtx.html