日期:2014-05-20  浏览次数:20843 次

Socket收和发可否放在两个不同的线程中处理?
各位好

小弟最近遇到了这个问题,我想将Socket 当server这端的收和发分开,一个线程专门进行收,另一个线程专门负责发。

ServerSocket mSocket = new ServerSocket(1234);

在收的线程里:
Socket socket = mSocket.accept();

那么在发的线程里,如何得到socket呢?...

先谢了

------解决方案--------------------
while(true){
ServerSocket mSocket = new ServerSocket(1234);
Client c = new Client(mSocket);
}
class Client implements Runable{
Socket s;
public Client(Socket s){
this.s = s;}
public void run(){
// 你的业务逻辑
}
}
------解决方案--------------------
Socket socket = mSocket.accept();不应该放在收的线程里,应该专门写一个线程接收用户请求,在接收到客户端的socket后把socket传给另一个线程,让它来处理与这个客户端的数据交互
Java code

Socket s=ss.accept();
Client c=new Client(s);
new Thread(c).start();

------解决方案--------------------
把socket变量做为全局变量试试,这样收和发两个线程都能看到
------解决方案--------------------
使用TCP协议来进行服务器端与客户端的通信

服务器端:
package com.aikaibo.network;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(5000);
//等待客服端的连接
Socket socket = ss.accept();

OutputStream os = socket.getOutputStream();

os.write("hello".getBytes());

InputStream is = socket.getInputStream();

byte[] buffer = new byte[200];
int length = is.read(buffer);

System.out.println(new String(buffer, 0, length));

// byte[] buffer = new byte[200];
//
// int length = 0;
//
// while(-1 != (length = is.read(buffer, 0, buffer.length)))
// {
// String str = new String(buffer, 0, length);
// System.out.println(str);
// }

os.close();
ss.close();
socket.close();
}
}


客户端:

package com.aikaibo.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TcpClient
{
public static void main(String[] args) throws Exception, IOException
{
//与服务器端建立好连接
Socket socket = new Socket("192.168.1.6", 5000);

InputStream is = socket.getInputStream();

byte[] buffer = new byte[200];

int length = is.read(buffer);

System.out.println(new String(buffer, 0, length));
// int length = 0;
// while(-1 != (length = is.read(buffer, 0, buffer.length)))
// {
// String str = new String(buffer, 0, length);
//
// System.out.println(str);
// }

OutputStream os = socket.getOutputStream();

os.write("wo".getBytes());
is.close();
os.close();
socket.close();
}
}