|
最近看一本书,里面有个例子,关于网络编程方面的,如下:
1、服务端DatagramServer1 :
import java.io.*;
import java.net.*;
import java.util.*;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2017</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class DatagramServer1 extends Thread{
DatagramSocket socket;
DatagramPacket packet;
int client;
public DatagramServer1(DatagramSocket socket,DatagramPacket packet,int client) {
this.socket = socket;
this.packet = packet;
this.client = client;
this.start();
}
public void run(){
try {
byte[] received = packet.getData();
System.out.println("Received from clinet = "+client+" "+new String(received));
String response = "You are client"+client;
byte[] buf = received;
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf,buf.length,address,port);
socket.send(packet);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args)throws Exception{
DatagramSocket socket = new DatagramSocket(4444);
System.out.println("Server Started");
byte[] buf = new byte[200];
int i = 1;
try {
while(true){
DatagramPacket packet = new DatagramPacket(buf,buf.length);
System.out.println("Waiting for client = "+i);
socket.receive(packet);
new DatagramServer1(socket,packet,i);
i++;
}
} catch (Exception ex) {
ex.printStackTrace();
}finally{
socket.close();
}
}
}
2、客户端
import java.io.*;
import java.net.*;
import java.util.*;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2017</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class DatagramClient {
public DatagramClient() {
}
public static void main(String[] args) throws IOException{
if(args.length!=2){
System.out.println("Usage:"+"java DatagramClient <hostname> <message>");
return;
}
DatagramSocket socket = new DatagramSocket();
System.out.println("My message="+args[1]);
byte[] buf = new byte[200];
buf = args[1].getBytes();
InetAddress address = InetAddress.getByName(args[0]);
DatagramPacket packet = new DatagramPacket(buf,buf.length,address,4444);
socket.send(packet);
packet = new DatagramPacket(buf,buf.length);
socket.receive(packet);
String received = new String(packet.getData());
System.out.println("The server returns my message:"+received);
socket.close();
}
}
问题在于:
比如:java DatagramClient hostName abc(hostName为主机名)
客户机第一次向服务器输出了3个字符abc,服务器、客户机均显示正常
第二次:java DatagramClient hostName 12,客户机真诚,但服务器显示12c
服务器程序好像没有清除调似的!!?
相关语句:byte[] received = packet.getData();
System.out.println("Received from clinet = "+client+" "+new String(received));
如题,本人初学不久,对这个问题深感迷惑,请教大虾~谢谢!!
|
|