Java socke 编程问题,求解答
我想实现多个客户端和一个服务端之间的互相传送报文,现在只做到了客户端向服务端传送,不能双向传送,求解怎么才能做到双向发送报文
2014-07-30 13:38
程序代码:
package beta;
import *;
import *;
class ServerThreadCode extends Thread
{
//客户端的socket
private Socket clientSocket;
//IO句柄
private BufferedReader sin;
private PrintWriter sout;
//默认的构造函数
public ServerThreadCode()
{}
public ServerThreadCode(Socket s) throws IOException
{
clientSocket = s;
//初始化sin和sout的句柄
sin = new BufferedReader(new InputStreamReader(clientSocket
.getInputStream()));
sout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream())), true);
//开启线程
start();
}
//线程执行的主体函数
public void run()
{
try
{
//用循环来监听通讯内容
for(;;)
{
String str = sin.readLine();
//如果接收到的是byebye,退出本次通讯
if (str.equals("byebye"))
{
break;
}
System.out.println("In Server reveived the info: " + str);
sout.println(str);
}
//System.out.println("closing the server socket!");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
//System.out.println("close the Server socket and the io.");
try
{
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public class ThreadServer {
//端口号
static final int portNo = 3333;
public static void main(String[] args) throws IOException
{
//服务器端的socket
ServerSocket s = new ServerSocket(portNo);
System.out.println("The Server is start: " + s);
try
{
for(;;)
{
//阻塞,直到有客户端连接
Socket socket = s.accept();
//通过构造函数,启动线程
new ServerThreadCode(socket);
}
}
finally
{
s.close();
}
}
}
2014-07-30 13:40
程序代码:package beta;
import *;
import *;
class ClientThreadCode extends Thread
{
//客户端的socket
private Socket socket;
//线程统计数,用来给线程编号
private static int cnt = 0;
private int clientId = ++cnt;
private BufferedReader in;
private PrintWriter out;
//构造函数
public ClientThreadCode(InetAddress addr)
{
try
{
socket = new Socket(addr, 3333);
}
catch(IOException e)
{
e.printStackTrace();
}
//实例化IO对象
try
{
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//开启线程
start();
}
catch(IOException e)
{
//出现异常,关闭socket
try
{
socket.close();
}
catch(IOException e2)
{
e2.printStackTrace();
}
}
}
//线程主体方法
public void run()
{
try
{
out.println("35|000"+clientId+"|clienta"+clientId+"|00"+clientId+clientId+"|2014-07-30-10-00-00 ");
String str = in.readLine();
System.out.println(str);
out.println("byebye");
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
public class ThreadClient {
public static void main(String[] args)
throws IOException, InterruptedException
{
int threadNo = 0;
InetAddress addr =
InetAddress.getByName("localhost");
for(threadNo = 0;threadNo<2;threadNo++)
{
new ClientThreadCode(addr);
}
}
}
2014-07-30 13:40
2014-07-30 13:41
2014-07-30 14:13
2014-07-30 14:48
2014-07-30 14:51
2014-07-30 14:51
2014-07-30 14:56