socket 聊天程序 急急急!!!
socket 怎么做到客户发一条服务器接受一条,再发给另一个客户端,如此循环往复
------解决方案--------------------package com.lh.socket;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import
java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTcpListener implements Runnable
{
public static void main(String[] args)
{
try
{
final ServerSocket server = new ServerSocket(ClientTcpSend.port);
Thread th = new Thread(new Runnable()
{
@Override
public void run()
{
while(true)
{
System.out.println("开始监听.....");
Socket socket = null;
try
{
socket = server.accept();
}
catch (
IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("有链接...");
receiveFile(socket);
}
}
});
th.run();
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
@Override
public void run()
{
// TODO Auto-generated method stub
}
public static void receiveFile(Socket socket)
{
byte [] inputByte = null;
int length = 0;
DataInputStream dis = null;
FileOutputStream fos = null;
try
{
try
{
dis = new DataInputStream(socket.getInputStream());
fos = new FileOutputStream(new File("D:/aa.jpg"));
inputByte = new byte[1024 * 4];
System.out.println("开始接受数据。。。");
while((length = dis.read(inputByte, 0, inputByte.length)) > 0)
{
fos.write(inputByte, 0, length);
fos.flush();
}
System.out.println("完成接受...");
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
finally
{
if(fos != null)
fos.close();
if(dis != null)
dis.close();
if(socket != null)
socket.close();
}
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
}
------解决方案--------------------
对的,就弄个死循环,首先Client发送,然后Server接收,然后Server发送,Client接收。
两边都起DataInputStream和DataOutputStream吧。不过一般是客户端只接收Client的连接,然后保存每一个Client的连接,然后Client发送一句,首先发到Server,Server再转发给其他客户端