我搜索了太多但没有得到答案,我实际上是在局域网中将数据包从客户端应用程序发送到服务器应用程序,会有多个客户端将数据包发送到服务器,另一端的服务器会只需从客户端应用程序接收这些数据包并将数据包存储在数据库中,服务器不会向客户端发送任何回复,我的服务器是否需要使用线程类进行线程化?还请告诉我我们什么时候需要线程客户端或服务器?
在此先感谢您的帮助。
public class MainActivity extends Activity {
private DatagramSocket socket;
String str;
EditText et;
Button bt;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "192.168.1.255";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button)findViewById(R.id.myButton);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
et = (EditText) findViewById(R.id.EditText01);
str = et.getText().toString();
new Thread(new ClientThread()).start();
}
});
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DatagramPacket packet = newDatagramPacket(str.getBytes(),str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}