Socket编程之前都是同时编写客户端和服务器,那样会非常不方便,调试也不容易。
因此,我使用了一个socket工具 叫《socket调试工具》,大家可以百度下载哈。有tcp客户端、tcp服务器、udp客户端、udp服务器、还有udp组,功能很强大。
TCP Server的源码如下,实现了echo的功能,并支持多客户端处理。
import java.net.*;
import java.io.*;
class ServerSocketTest
{
public static void main(String[] args) throws Exception
{
ServerSocket server = new ServerSocket(8888);
Socket socket = null;
while((socket = server.accept())!=null)
{
System.out.println("client"+socket.getRemoteSocketAddress()+"connected");
new Thread(new client(socket)).start();
}
//System.out.println("Hello World!");
}
}
class client implements Runnable
{
private Socket socket;
OutputStream out;
InputStream in;
public client(Socket s)
{
socket = s;
}
public void run()
{
try{
out = socket.getOutputStream();
in = socket.getInputStream();
}catch(IOException e)
{}
byte[] buf = new byte[1024];
while(true)
{
try{
int n = in.read(buf);
String s = new String(buf,0,n,"UTF-8");
System.out.println(s);
out.write(buf);
}catch(IOException e)
{
}
}
}
}
UDP,UDP说白了就是组包,发送的过程,代码如下:(写得非常草,不好意思)
import java.net.*;
import java.io.*;
class DatagramSocketTest
{
public static void main(String[] args) throws Exception
{
DatagramSocket socket = new DatagramSocket(7777);
byte[] b = new byte[1024];
DatagramPacket packet = new DatagramPacket(b,b.length);
socket.receive(packet);
System.out.println(new String(b,"UTF-8"));
System.out.println("Hello World!");
}
}