那是因为你用的是tcp短连接通信。应该用长连接通信。
解决方案 »
- 谁有J2EE的中文API?给小弟发一个啊。。。。。
- Hibernate怎样用update加in语句,高手请进,急急!!
- System.setProperty 与 System.getProperty
- 关于Flex与JEE项目
- java内存泄露是错误还是异常
- 请问大家是如何学习SSH的
- 用Hibernate插入数据,主键取数据库的Sequence,为何都是2,4…………?
- struts图书下载!!!
- 一个关于java的map类的应用想法,不知可否实现,特高人请教!
- 哪里可以下载到J2SDKEE,我到SUN的网站找不到,能给出下载链接吗?
- java
- 关于java *.properties配置文件格式的问题
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;public class Server implements Runnable { private ServerSocket serverSocket;
private int listenPort;
public Server(int listenPort) {
super();
this.listenPort = listenPort;
} @Override
public void run() {
Socket socket = null;
InputStream in = null;
try {
serverSocket = new ServerSocket(listenPort);
System.out.println("Server is listening ... ");
socket = serverSocket.accept();
in = socket.getInputStream();
byte[] inContents = new byte[1024];
while (in.read(inContents) != -1) {
System.out.println(new String(inContents));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try { socket.close(); } catch (IOException e) { e.printStackTrace(); }
socket = null;
}
if (serverSocket != null) {
try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); }
serverSocket = null;
}
if (in != null) {
try { in.close(); } catch (IOException e) { e.printStackTrace(); }
in = null;
}
}
}
public static void main(String[] args) {
Server server = new Server(17901);
new Thread(server).start();
}
}Client 端:
package com.csdn.wyq.socket;import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;public class Client implements Runnable { private Socket socket;
/**
* @param args
*/
public static void main(String[] args) {
Client client = new Client();
new Thread(client).start();
} @Override
public void run() {
OutputStream out = null;
try {
socket = new Socket("127.0.0.1", 17901);
out = socket.getOutputStream();
String str = "Hello\n";
while (true) {
out.write(str.getBytes());
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null) {
try { socket.close(); } catch (IOException e) { e.printStackTrace(); }
socket = null;
}
if (out != null) {
try { out.close(); } catch (IOException e) { e.printStackTrace(); }
out = null;
}
}
}}