import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetServerSocket;
import javanetSocket;
publicclass Server
{
private ServerSocket ss;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Server()
{
try
{
ss = new ServerSocket(10000);
while (true)
{
socket = ssaccept();
String RemoteIP = socketgetInetAddress()getHostAddress();
String RemotePort = ":" + socketgetLocalPort();
Systemoutprintln("A clientcome in!IP:" + RemoteIP
+ RemotePort);
in = new BufferedReader(new
InputStreamReader(socketgetInputStream()));
String line = inreadLine();
Systemoutprintln("Cleint sendis :" + line);
out = new PrintWriter(socketgetOutputStream(), true);
outprintln("YourMessage Received!");
outclose();
inclose();
socketclose();
}
}
catch (IOException e)
{
outprintln("wrong");
}
}
publicstaticvoid main(String[] args)
{
new Server();
}
}
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetSocket;
publicclass Client {
Socket socket;
BufferedReader in;
PrintWriter out;
public Client()
{
try
{
Systemoutprintln("Try toConnect to 127001:10000");
socket = new Socket("127001", 10000);
Systemoutprintln("The ServerConnected!");
Systemoutprintln("Pleaseenter some Character:");
BufferedReader line = new BufferedReader(new
InputStreamReader(Systemin));
out = new PrintWriter(socketgetOutputStream(), true);
outprintln(linereadLine());
in = new BufferedReader(new InputStreamReader(socket
getInputStream()));
Systemoutprintln(inreadLine());
outclose();
inclose();
socketclose();
}
catch (IOException e)
{
outprintln("Wrong");
}
}
publicstaticvoid main(String[] args)
{
new Client();
}
}
你再改改代码就可以了但我没时间帮你调了……这个很简单啊。设置超时就可以了,当超过一定时间没有进行数据交换的话,会自动关闭的。或者写个监护线程,查看状态。socket还有一个方法叫isClose也可以进行判断。楼下的是sice5921:是2货来到的,来混分的楼主千万别给分他,像这种拉基进来一次检举一次,哪怕把问题关闭了也不给这种拉基分首先建议使用一个线程向所有客户端发送消息;
在写一个方法发送消息, 方法里面需要 消息和socket 参数;
Thread tSend= new Thread(SendAll);
private void SendAll()
{
//遍历所有的Socket,调用Send(string msg,Socket socket)方法
//不知道你的Socket放到哪里,如果放到集合就遍历集合挨个调用
}
private void Send(string msg,Socket socket)
{
byte[] buffer = EncodingDefaultGetBytes(msg);
socketSend(buffer);
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)