本帖最后由 张华廷 于 2012-6-23 19:45 编辑
import java.io.*;
import java.net.*;
/*
tcp 传输,客户端和服务端的互访
*/
// 建立socket服务,指定连接主机和端口
//获取socket流中的输出流,将数据写到流中,通过网络发给服务端
//获取socket流中的输入流,将服务端反馈的数据获取到,并打印
//关闭客户端
class TcpClient2
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("192.168.1.254",10004);
OutputStream out = s.getOutputStream();//拿到输出流对象
out.write("服务端,你好".getBytes());
InputStream in =s.getInputStream();
byte[] buf =new byte[1024];//建立缓冲区
int len = in.read(buf);
System.out.println(new String(buf,0,len));
s.close();
}
}
class TcpServer2
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10004);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();//拿到客户端地址
System.out.println(ip+"........congnent");
InputStream in = s.getInputStream();//先读一次数据
byte[] buf = new byte[10004];//缓冲区
int len = in.read(buf);
System.out.println(new String(buf,0,len));
OutputStream out = s.getOutputStream();//服务端反向
out.write("收到,你也好".getBytes());
s.close();
ss.close();
}
}
服务端编译通过,客户端编译出现Exception in thread "main" java.lang.NoClassDefFoundError: TcpClient
Caused by: java.lang.ClassNotFoundException: TcpClient
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: TcpClient. Program will exit.
|
|