在Socket编程中怎么实现server端和client端的永远连接,在我的代码中client和server只能连一次,而不能持续连接,就是一连接上就不断开了,谢谢!
解决方案 »
- 急急急!!求助!!见代码给分儿
- 打开文件的问题?
- 祝贺:java学习交流 QQ群 开通 号码:19105801
- 哪位帮个忙,给个《核心卷I、II》的最新英文版下载地址
- 请问现在企业一般性用什么java编译器????
- 我想做一个 登录的窗体?
- 为何出现这个错误:java.sql.SQLException: 对只读结果集的无效操作: updateString;code如下:
- 请教!100分.....
- 有谁能说一下中国人现在分那些层次?
- vj编程时,调用函数时总是出现某函数被java.awt.component的作者抵抗,这是怎么回事,如何解决?
- 如何写JTextField 监听text.addActionListener事件
- JAVA读取多个同名的properties文件,高手解答
..... //连起来
}
还可以实现在服务器接受多个客户端的同时接入。把接收连接请求的全码放在死循环中就可以了。
try {
ss = new ServerSocket(8888);
while(boo){
s = ss.accept(); dis = new DataInputStream(s.getInputStream());
while(boo){
String str = dis.readUTF();
System.out.println(str);
//dis.close();
}
}
} catch (IOException e) {
System.out.println("connection off");
} finally {
try {if (ss != null)
ss.close();
if (s != null)
s.close();
dis.close();
}catch (IOException e1){
e1.printStackTrace();
}
}
}
private void connection(){ //client
try {
s = new Socket("127.0.0.1",8888);
System.out.println("socket connected.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;public class SocketExample
{
/**
* @param args
*/
public static void main(String[] args)
{ try
{
ServerSocket ss = new ServerSocket(5050);
while (true)
{
Socket s = ss.accept();
Thread t = new Thread(new Dispatcher(s));
t.start();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static class Dispatcher implements Runnable
{
private DataInputStream dis;
private DataOutputStream dos;
private Socket s;
public Dispatcher(Socket s)
{ this.s = s;
try
{
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run()
{ while (true)
{
try
{
String msg = dis.readUTF();
dos.writeUTF("Hello World:" + msg);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}