java 网络编程-tcp/udp

时间:2022-03-31 20:28:02

--转自:http://blog.csdn.net/nyzhl/article/details/1705039

直接把代码写在这里,解释看这里吧:http://blog.csdn.net/nyzhl/article/details/1705039

Java UDP网络编程主要通过 DatagramSocket和DatagramPacket 两个类实现的,下面是一个示例程序,
Server监听UDP 2000端口并把收到的Long类型数值打印出来
Client则通过输入获得Long类型的数值,并把它发给Server

Server:

package com.sas ;
import java.net.*;
import java.io.*; public class DatagramServer {
public static void main (String[] args) {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(2000);
}
catch (SocketException e) {
e.printStackTrace();
System.exit(-1);
}
byte[] buffer = new byte[1024];
DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
while (true) {
DataInputStream in = new DataInputStream (
new ByteArrayInputStream (buffer)
);
try {
ds.receive(dp);
System.out.println(in.readLong());
in.close();
}
catch (IOException e) {
e.printStackTrace();
continue;
}
}
//ds.close(); JDK提示"无法访问的语句"
//因为前面是死循环,无论如何也执行不到后面的语句
}
}

Client:

package com.sas;
import java.net.*;
import java.io.*; public class DatagramClient {
public static void main (String[] args) {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
}
catch (SocketException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("输入一个数字:");
BufferedReader typeReader = new BufferedReader (
new InputStreamReader(System.in)
);
long data = 0;
while(true) {
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream (bytesOut);
try {
data = Long.parseLong(typeReader.readLine());
dataOut.writeLong(data);
dataOut.flush();
byte[] buffer = bytesOut.toByteArray();
DatagramPacket dp = new DatagramPacket(
buffer,
buffer.length,
new InetSocketAddress("127.0.0.1",2000)
);
ds.send(dp);
dataOut.close();
bytesOut.close();
}
catch (SocketException e) {
System.err.println("Socket Error!");
continue;
}
catch (IOException e) {
System.err.println("IO Error!");
continue;
}
catch (Exception e) {
e.printStackTrace();
continue;
}
}
//ds.close(); JDK提示"无法访问的语句"
//因为前面是死循环,无论如何也执行不到后面的语句
}
}

TCP实现:

client:

package com.sas;

import java.io.OutputStreamWriter;
import java.net.Socket; public class TCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1",2000);
OutputStreamWriter w = new OutputStreamWriter(s.getOutputStream());
w.write("Hello服务器");
w.flush();
w.close();
s.close();
}
}

server:

package com.sas;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket; public class TCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(2000);
while(true) {
Socket s = ss.accept();
System.out.println("A client has heen connected.");
InputStreamReader r = new InputStreamReader(s.getInputStream());
int c = 0;
while((c=r.read())>-1) {
System.out.print((char)c);
}
System.out.println();
r.close();
s.close();
}
}
}