{
while (true)
{
try
{
byte[] buf = new byte[1024]/* 接收端程序,设置BUF数组长度为1024位 */
DatagramPacket dp = new DatagramPacket(buf, buf.length)/* 创建接收数据报的实例 */
ds.receive(dp)
lst.add("他说:" + new String(buf), 0)
} catch (IOException ex)
{
}
}
}
======================
线程的run方法改成上面这样就可以了,原因是因为接收端每次循环都是使用的同一个buf,而buf没有清空,所以导致每次接收都只更新前面一小段信息,后面的信息没有改变。
使用DatagramSocket和DatagramPacket其中DatagramSocket使用一个发送的端口号
DatagramPacket的参数
DatagramPacket(bytes[] bytes,int bytes[].length,InetAddress ip, int port)里的port就是目标端口
要向两个端口号发送,需要创建两个DatagramPacket,分别填写两个IP地址和端口号,并用DatagramSocket发送。
另外两个端口需要做监听
要注意ip要为局域网可以畅通无阻,广域网可能导致网管阻止
下面是个例子,发两遍即可。
int SERVER_PORT=7000
String severIp="192.168.1.100"
DatagramSocket clientSocket
try
{
InetAddress local = InetAddress.getByName(severIp)
DatagramPacket dPacket
clientSocket = new DatagramSocket
dPacket = new DatagramPacket("Hello".getBytes("utf-8"),"Hello".getBytes("utf-8").length,
local, SERVER_PORT)
clientSocket.send(dPacket)//这里是发送
byte[] msg = new byte[11246]
DatagramPacket rPacket = new DatagramPacket(msg, msg.length)
clientSocket.receive(rPacket)//这里是接收监听
}
catch (IOException e)
{
e.printStackTrace()
}
clientSocket.close()
Server端:import java.io.*
import java.net.*
import java.applet.Applet
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null
try{
server=new ServerSocket(4700)
}catch(Exception e) {
System.out.println("can not listen to:"+e)
}
Socket socket=null
try{
socket=server.accept()
}catch(Exception e) {
System.out.println("Error."+e)
}
String line
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()))
PrintWriter os=new PrintWriter(socket.getOutputStream())
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in))
System.out.println("Client:"+is.readLine())
line=sin.readLine()
while(!line.equals("bye")){
os.println(line)
os.flush()
System.out.println("Server:"+line)
System.out.println("Client:"+is.readLine())
line=sin.readLine()
}
os.close()
is.close()
socket.close()
server.close()
}catch(Exception e){
System.out.println("Error:"+e)
}
}
}
Client端:
import java.io.*
import java.net.*
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700)
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in))
PrintWriter os=new PrintWriter(socket.getOutputStream())
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()))
String readline
readline=sin.readLine()//从系统标准输入读入一字符串
while(!readline.equals("bye")){
os.println(readline)
os.flush()
System.out.println("Client:"+readline)
System.out.println("Server:"+is.readLine())
readline=sin.readLine()//从系统标准输入读入一字符串
}
os.close()//关闭Socket输出流
is.close()//关闭Socket输入流
socket.close()//关闭Socket
}catch(Exception e) {
System.out.println("Error"+e)//出错,则打印出错信息
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)