readutf异常_java.io.EOFException

java.io.EOFException

java.io.EOFException

服务端:publicclasst10_5_sextendsJFrame{privateServerSocketserver;privateSocketsock;privateDataInputStreamdis;privateDataOutputStreamdos;privateFileInputStreamfis;privat...

7

热度

总是报java.io.EOFException

RMS中readUTF()读取记录问题,急!!!RMS中readUTF()读取记录问题,现在情况是无法判断readUTF是否读出数据出来,总是报java.io.EOFException'>java.io.EOFException异常,程序就死掉了,我想能否人工判断是否为空,让程序继续执行下去,用dis.readUTF()就报错!不知道怎么处理了,各位高手帮帮忙啊!!!!color='#e78608...

4029

热度

惊人: IOException while loading persisted sessions: java.io.EOFException

严重:IOExceptionwhileloadingpersistedsessions:java.io.EOFException

tomcat在启动时出现如下异常问题:严重:IOExceptionwhileloadingpersistedsessions:java.io.EOFException严重:Exceptionloadingsessionsfrompersistentstorage解决方案...

7

热度

Java网络TankServer端抛错!java.io.EOFException

Java网络TankServer端抛错!java.io.EOFException

我这里在做一个用Java写的坦克大战的练习,写这个网络版时,我的Server要保存客户端的UdpPort,

可在起了server后,提示intudpPort=dis.readInt();这里抛异常java.io.EOFException,可我后面不是已经都catch了,怎么还会有这个异...

7

热度

Tomcat:IOException while loading persisted sessions: java.io.EOFException错误处理

Tomcat:IOExceptionwhileloadingpersistedsessions:java.io.EOFException异常处理

网上查看得出的结论:出现原因:tomcat对保存硬盘的session读取失败解决方法:打开TOMCAT的安装目录,在WORK文件夹找到Catalina/localhost/你的工程名所在文件夹下,把里面的session.ser删除即可。但是我进入到我的项...

3

热度

惊人: IOException while loading persisted sessions: java.io.EOFException java.i

严重:IOExceptionwhileloadingpersistedsessions:java.io.EOFExceptionjava.i

java">

严重:IOExceptionwhileloadingpersistedsessions:java.io.EOFException

java.io.EOFException

atjava.io.ObjectInputStream$PeekInpu...

7

热度

tomcat起动报:严重: IOException while loading persisted sessions: java.io.EOFException

tomcat启动报:严重:IOExceptionwhileloadingpersistedsessions:java.io.EOFException

严重:IOExceptionwhileloadingpersistedsessions:java.io.EOFExceptionjava.io.EOFExceptionatjava.io.ObjectInputStream$PeekInputStre...

6

热度

java.io.EOFException这是个什么错误应该如何解决

java.io.EOFException'>java.io.EOFException这是个什么异常应该怎么解决?第一个类publicfunctionserver(intport){this.port=port;try{ss=newServerSocket(port);System.out.println("服务器套接字已经创建成功");//收到信息后处理while(true){...

94

热度

很简单的序列化程序,抛出io.EOFException 错误

很简单的序列化程序,抛出io.EOFException'>EOFException异常大家好,我写了一个很简单的序列化程序,该程序把一个整数写入文件,再从该文件读出这个整数,可却跑出了OFException异常:Javacodeimportjava.io.*;publicclassTest{publicstaticvoidmain(String[]args)throwsException{Obje...

549

热度

java EOFException 和 发送对象问题

javaEOFException和发送对象问题

QuestionOne

求助EndOfFile异常..........

--------------

我在写Socket的时候遇到的问题,我想我也知道问题在什么地方

可是就是没有办法解决.........

客户端在使用Socket连接成功后,使用DataOutputStream发送一个标记字符串

里面记录用户的基本...

7

热度

java io 读写对照

javaio读写对比用javaio读写对象分别对100mb?500mbtxt文档做读写性能对比。??

5568

热度

tomcat启动时loading persisted sessions报IOException的解决办法

tomcat启动时loadingpersistedsessions报IOException的解决方法

今天启动tomcat7的时候,突然发发现有错误信息:16/11/20114:57:11PMorg.apache.catalina.session.StandardManagerdoLoadSEVERE:IOExceptionwhileloadingpersistedsessions:java.io...

1

热度

个人资料Java io源

个人资料Javaio流

个人资料Javaio流

1

热度

j2me访问域名有关问题

j2me访问域名问题!我用j2me通过IP访问Servlet,通过readUTF()读取没有问题,但是通过域名访问时通过readUTF()读取就发生java.io.EOFException'>java.io.EOFException异常,代码如下:if(http.getResponseCode()==HttpConnection.HTTP_OK){System.out.println("...

9176

热度

Spring - java.io.FileNotFoundException

Spring-java.io.FileNotFoundException

通过以下语句请求test.jsp页面:(Spring)publicModelAndView(HttpServletRequestrequest,HttpServletResponseresponse){......returnnewModelAndView(request.getContextPa...

17

热度

java IO stream的问题

javaIOstream的问题

1、从键盘上输入一些字符,可以有回车,以”#”结束输入;将输入的这些字符写到文本文件”a.txt”中

2、读取”a.txt”中的内容,计算字符数和行数

求解

搜索更多相关的解决方案:

java"target="_blank">color="red">javacolor="red">文本文件color="red"...

10

热度

java io换行的问题

javaio换行的问题

importjava.io.*;publicclassRomd{publicstaticvoidmain(String[]args)throwsIOException{RandomAccessFileraf=newRandomAccessFile("e:\\test.txt","rw");BufferedReaderbuf=newBuffered...

6

热度

[转载]彻底明白Java的IO系统

[转载]彻底明白Java的IO系统

彻底明白Java的IO系统一.Input和Output1.stream代表的是任何有能力产出数据的数据源,或是任何有能力接收数据的接收源。在Java的IO中,所有的stream(包括Input和Outstream)都包括两种类型:1.1以字节为导向的stream以字节为导向的stream,表示以字节为单位从stream中读取或往str...

2

热度

Java语言深入JAVA之精粹IO流

Java语言深入JAVA之精髓IO流

Java语言深入JAVA之精髓IO流

?

一.Input和Output1.stream代表的是任何有能力产出数据的数据源,或是任何有能力接收数据的接收源。在Java的IO中,所有的stream(包括Input和Outstream)都包括两种类型:1.1以字节为导向的stream以字节为导向的stream,表示以字节为单位从stream中读...

1

热度

java.io.File 这个种

java.io.File这个类java.io.File类代表系统文件名,并不代表实际当中物理上的文件,物理上的文件就是硬盘上的一段空间,里面装了好多数据,要读数据通过file类读不出来,只能通过io流才能读出来,File这个类只能代表一个文件名(路径和文件名),file有可能是路径或者是文件名,当new一个File类的时候并不是真的在硬盘上建立了一个文件,而是只是在内存当中建立了一个名字是file...

5022

热度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
IO ============================================================================================================================================= * Input /Output 输入 输出 保存文件 读取文件 java.iojava.io.File ============================================================================================ *表示磁盘文件或目录的路径 *可以表示一个不存在的路径 创建实例 ------------------------------------- 1 File f=new File("d:/abc") (d:\\abc) 2 File f=new File ("目录","文件名") 创建一个 File 封装对象 可以不存在 方法 -------------------------------------------- 文件、目录属性方法 文件、目录属性 canRead() canWrite() canExecute() 是否可读可写可执行 isHidden() 是否隐藏文件 exists() 表示的路径是否存在 getAbsolutePath() 完整路径 getName() 文件名 getParent() 父目录 lastModified() 最后修改时间,毫秒值 length() 文件字节量,对目录无效 isDirectory() 是否文件夹 isFile() 是否文件 getTotalSpace() 空间总大小 getFreeSpace() 可用空间 文件、目录操作 createNewFile() 创建文件 delete() 删除文件或“空目录” mkdir() 创建单层目录 mkdirs() 创建多层目录 renameTo() 改名、移动 *) 创建删除重命名方法返回 boolean,表示操作是否成功 File.createTempFile() 在系统临时目录创建临时文件 目录列表 list() 返回 String[],包含子文件、子目录名称 listFiles() 返回 File[],包含子文件、子目录的 File 对象 list(FilenameFilter) listFiles(FilenameFilter) listFiles(FileFilter) 只列出符合过滤条件的文件、目录, 参数: 外接的过滤器 private static void test1() { // File f=new File("d:/rand.txt"); // File f=new File("d:/abad"); File f=new File("d:/scq"); System.out.println("是否可读:"+f.canRead()); System.out.println("是否可写:"+f.canWrite()); System.out.println("是否是隐藏:"+f.isHidden()); System.out.println("文件的绝对路径:"+f.getAbsolutePath()); System.out.println("获得文件名:"+f.getName()); System.out.println("获得父类目录名:"+f.getParent()); System.out.println("获得最后一次修改时间:"+f.lastModified()); System.out.println("文件字节量:"+f.length()); System.out.println("是否是目录:"+f.isDirectory()); System.out.println("是否是文件:"+f.isFile()); System.out.println("获得总空间大小:"+f.getTotalSpace()); System.out.println("获得剩余空间大小:"+f.getFreeSpace()); } 文件目录操作方法 public class Test2 { /** * @author aibin zhang * @param args * @throws IOException */ public static void main(String[] args) throws IOException { test4(); } //创建临时文件 文件名称不能太短 private static void test4() throws IOException { File f = File.createTempFile("abc", ".txt"); System.out.println(f.getAbsolutePath()); } // 测试renameto方法 移动和更改问价名 private static void test3() { File f1 = new File("d:/rand.txt"); File f2 = new File("d:/r.txt"); // 刚改前查看文件是否存在 System.out.println(f1.getName() + "是否存在" + f1.exists()); System.out.println(f2.getName() + "是否存在" + f2.exists()); // 使用renameto方法 System.out.println("文件名是否更改成功:" + f1.renameTo(f2)); // 改名以后的的状态 System.out.println(f1.getName() + "是否存在" + f1.exists()); System.out.println(f2.getName() + "是否存在" + f2.exists()); } // 测试创建单层目录mkdir和多层目录mkdirs private static void test2() { File f = new File("d:/dir1/dir2"); if (f.exists()) { System.out.println("是否成功删除:" + f.delete()); // 获得父类目录文件对象实例调用delete方法删除 f.getParentFile().delete(); } else { System.out.println("是否成功创建:" + f.mkdirs()); } } // 测试创建和删除文件 private static void test1() throws IOException { File f = new File("d:/f1.dlkjkajsdklgjexe"); if (f.exists()) {// 是够存在此文件 System.out.println("是否成功删除:" + f.delete()); } else { System.out.println("是否成功创建:" + f.createNewFile()); } } } 目录列表 --------------------------------------------------------------------------------- list listFlie list(FilenameFilter ) 文件名称过滤器 listFiles(FilenameFilter) 文件属性过滤器 public class Test1 { public static void main(String[] args) { test1(); } /////////////////////2014-8-23文件筛选操作 private static void test1() { File f=new File("D:/bookandimage"); String [] name=f.list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".zip"); } }); File [] files=f.listFiles(new FileFilter() { public boolean accept(File f) { return f.length()>=20*1024; } }); for (File file : files) { int len=(int) (file.length()/1024); System.out.println(file.getName()+"---"+len+"KB"); } for( String na : name) { System.out.println(na); } } } ///////////查看目录大小 // 主要用到的是 listfiles isFile package tarena.day1802; import java.io.File; import java.util.Scanner; public class Test1 { public static void main(String[] args) { System.out.println("输入目录:"); String path=new Scanner(System.in).nextLine(); File dir=new File(path); long len=dirLength(dir); System.out.println(len/1024+"KB"); } private static long dirLength(File dir) { /* * 1 定义累加变量 long len * 2 获得目录列表 dir.listFiles赋给files * 3 判断files数组是否是null值 * 如果是null 返回return 0; * 5遍历从数组files取出的每个对象 赋给f * 6判断f是文件 * 获得文件大小累加到len * 否则是文件夹 * 再调用自身方法 dirLength * 求文件夹大小累加到len * return len; * */ long len=0; File [] files=dir.listFiles(); if(files==null){ return 0; } for (File file : files) { if(file.isFile()){ len+=file.length(); }else { len+=dirLength(file); } } return len; } } ////删除目录 public class Test1 { public static void main(String[] args) { System.out.println("输入目录名"); String path=new Scanner(System.in).nextLine(); File dir=new File(path); boolean success=dirDelete(dir); if(success){ System.out.println("删除成功!"); }else{ System.out.println("删除失败!!"); } } private static boolean dirDelete(File dir) { /* * 2 获得目录列表 dir.listFiles赋给files * 3 判断files数组是否是null值 * 并返货尝试直接删除是否成功; * 5遍历从数组files取出的每个对象 赋给f * 6判断f是文件 * 直接删除f * 如果删除返回false * 否则是文件夹 * 再调用自身方法dirDelete来删除文件夹f * 如果失败则返回false * 遍历结束 删除 dir * 如果失败则返回 * */ File[] files = dir.listFiles(); if(files==null)return dir.delete(); for (File file : files) { if(file.isFile()){ if(!file.delete())return false; }else{ if(!dirDelete(file))return false; } } return dir.delete(); } } ================================================================================== java.io.RandomAccessFile --------------------------------------------------------------- // ***用来读写文件 //将一个文件看做是一个字节数组 //用下标值访问摸个位置的字节值 创建实例 ----------------------- 1 RandomAccessFile raf= new RandomAccessFile(文件,“r”) r 只读模式 1 RandomAccessFile raf= new RandomAccessFile(文件,“rw”) r 读写模式 方法 ------------------------ 写字节 write() -------- -------- write (int b) 将int 四字节中的末尾字节 写到文件里 【1】【2】【3】【4】 --》【4】 write ( byte [] b) 将数组中所有字节值 全部写到文件 write (byte [] buf,int start ,int n) 将数组中的start开始位置,n个范围中的字节值,写到文件 读字节 read() --------- --------- read() 读取一个字节值,再前面补三个0字节 变成 int 类型 [4] --> [1][2][3][4] 如果没有数据,返回 -1; read ( byte[] buf) 根据数组的长度读取一批字节值,放入数组 一次读取的长度是数组的长度 返回每次存放到数组中的字节数量 如果没有数据 则返回 -1; seek(int position) 将指针定位到指定位置 public class Test1 { public static void main(String[] args) throws IOException{ /* * 如果文件不存在 自动新年检文件 * 如果文件夹不存在则出现FileNotFoundException、 * * */ RandomAccessFile raf=new RandomAccessFile("d:/f2.mp3", "rw"); //写入单个字节值 raf.write(97); raf.write(98); raf.write(99); raf.write(100); //写入一组数组字节 byte [] buf={101,102,103,104,105,106}; raf.write(buf); raf.write(buf,2,3); //调用seek 将指针调回 raf.seek(0); //读取文件字节 //单个字节读取 int b;//定义一个变量 int b 用来保存每次读取的字节值 while ((b=raf.read())!=-1){ System.out.println(b); } raf.seek(0); buf=new byte[5]; int n ; //用来保存每次读取或放入数组中的字节数量 while((n=raf.read(buf))!=-1){ System.out.print(n+"--"); System.out.println(Arrays.toString(buf)); // while循环最后会打印出重复数据 //for循环可以避免打印出重复数据 for (int i = 0; i < n; i++) { System.out.println(buf[i]); } } //关闭数据连接 raf.close(); } } print out 97 98 99 100 101 102 103 104 105 106 103 104 105 5--[97, 98, 99, 100, 101] 97 98 99 100 101 5--[102, 103, 104, 105, 106] 102 103 104 105 106 3--[103, 104, 105, 105, 106] 103 104 105 writeInt (int b ) 输出 int 的四个字节 writeDouble(double b) 输出 double 的八个字节 writeUTF(String s) 先输出2个字节 表示字符串的字节长度 在输出字符串的字节数据 readInt() 读取4个字节作为一个int值 readDouble () 读取8个字节作为一个double值 readUTF() 先读取2个字节来确定字符创长度 在读取字符串的字节值 EOFException read读取异常 public class Test2 { public static void main(String[] args) throws Exception { test1(); } private static void test1() throws Exception { RandomAccessFile raf=new RandomAccessFile("d:/f3.java", "rw"); raf.write(97); raf.writeInt(97); raf.writeDouble(3.14); raf.writeUTF("a中"); raf.seek(0); //从头到尾单字节输出 int b; while((b=raf.read())!=-1){ System.out.println(b); } System.out.println("****************************"); //从头到尾批量输出 raf.seek(0); byte [] buf=new byte[5]; while((b=raf.read(buf))!=-1){ System.out.println(b); System.out.println(Arrays.toString(buf)); } // //////////////////////////////////////////////// raf.seek(0); System.out.println("*********************************"); System.out.println("*********************************"); //read 是单字节读取 System.out.println(raf.read()); //读取int型数据 System.out.println(raf.readInt()); //读取Double类型数据 System.out.println(raf.readDouble()); //读取String类型数据 System.out.println(raf.readUTF()); raf.close(); } } getFilePointer() 获得指针当前位置 setLength(字节长度); 事先给数据把空间留足 可以将数据截取处理为指定长度 可以扩大数据物理空间为指定长度 -------------------------------------------------------------------------------- public class Test3 { /**@author aibin zhang * @param args */ public static void main(String[] args) { test1(); } private static void test1() { File f=new File("D:/bookandimage"); //转换成list String数组存放文件名称 String[] s=f.list(); //转换成listFiles file数组 File [] files=f.listFiles(); for (String s1 : s) { System.out.println(s1); } System.out.println("************************"); for (File file : files) { int l=(int) file.length()/1024/1024; System.out.println(file.getName()+"--"+l+"MB"); } } } 字段摘要 static String pathSeparator 与系统有关的路径分隔符,为了方便,它被表示为一个字符串。 static char pathSeparatorChar 与系统有关的路径分隔符。 static String separator 与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。 static char separatorChar 与系统有关的默认名称分隔符。 构造方法摘要 File(File parent, String child) 根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。 File(String pathname) 通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。 File(String parent, String child) 根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。 File(URI uri) 通过将给定的 file: URI 转换为一个抽象路径名来创建一个新的 File 实例。 方法摘要 boolean canExecute() 测试应用程序是否可以执行此抽象路径名表示的文件。 boolean canRead() 测试应用程序是否可以读取此抽象路径名表示的文件。 boolean canWrite() 测试应用程序是否可以修改此抽象路径名表示的文件。 int compareTo(File pathname) 按字母顺序比较两个抽象路径名。 boolean createNewFile() 当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。 static File createTempFile(String prefix, String suffix) 在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。 static File createTempFile(String prefix, String suffix, File directory) 在指定目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称。 boolean delete() 删除此抽象路径名表示的文件或目录。 void deleteOnExit() 在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。 boolean equals(Object obj) 测试此抽象路径名与给定对象是否相等。 boolean exists() 测试此抽象路径名表示的文件或目录是否存在。 File getAbsoluteFile() 返回此抽象路径名的绝对路径名形式。 String getAbsolutePath() 返回此抽象路径名的绝对路径名字符串。 File getCanonicalFile() 返回此抽象路径名的规范形式。 String getCanonicalPath() 返回此抽象路径名的规范路径名字符串。 long getFreeSpace() 返回此抽象路径名指定的分区中未分配的字节数。 String getName() 返回由此抽象路径名表示的文件或目录的名称。 String getParent() 返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。 File getParentFile() 返回此抽象路径名父目录的抽象路径名;如果此路径名没有指定父目录,则返回 null。 String getPath() 将此抽象路径名转换为一个路径名字符串。 long getTotalSpace() 返回此抽象路径名指定的分区大小。 long getUsableSpace() 返回此抽象路径名指定的分区上可用于此虚拟机的字节数。 int hashCode() 计算此抽象路径名的哈希码。 boolean isAbsolute() 测试此抽象路径名是否为绝对路径名。 boolean isDirectory() 测试此抽象路径名表示的文件是否是一个目录。 boolean isFile() 测试此抽象路径名表示的文件是否是一个标准文件。 boolean isHidden() 测试此抽象路径名指定的文件是否是一个隐藏文件。 long lastModified() 返回此抽象路径名表示的文件最后一次被修改的时间。 long length() 返回由此抽象路径名表示的文件的长度。 String[] list() 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。 String[] list(FilenameFilter filter) 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录。 File[] listFiles() 返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。 File[] listFiles(FileFilter filter) 返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录。 File[] listFiles(FilenameFilter filter) 返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录。 static File[] listRoots() 列出可用的文件系统根。 boolean mkdir() 创建此抽象路径名指定的目录。 boolean mkdirs() 创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。 boolean renameTo(File dest) 重新命名此抽象路径名表示的文件。 boolean setExecutable(boolean executable) 设置此抽象路径名所有者执行权限的一个便捷方法。 boolean setExecutable(boolean executable, boolean ownerOnly) 设置此抽象路径名的所有者或所有用户的执行权限。 boolean setLastModified(long time) 设置此抽象路径名指定的文件或目录的最后一次修改时间。 boolean setReadable(boolean readable) 设置此抽象路径名所有者读权限的一个便捷方法。 boolean setReadable(boolean readable, boolean ownerOnly) 设置此抽象路径名的所有者或所有用户的读权限。 boolean setReadOnly() 标记此抽象路径名指定的文件或目录,从而只能对其进行读操作。 boolean setWritable(boolean writable) 设置此抽象路径名所有者写权限的一个便捷方法。 boolean setWritable(boolean writable, boolean ownerOnly) 设置此抽象路径名的所有者或所有用户的写权限。 String toString() 返回此抽象路径名的路径名字符串。 URI toURI() 构造一个表示此抽象路径名的 file: URI。
Java 网络编程 说明: 网络编程,分为两种一种是TCP、另一种是UDP方式。我们分别写一下TCP、UDP端的Server和Client简单演示代码。 TCP: Sever import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) { try { ServerSocket socket = new ServerSocket(4444); while (true) { Socket sc =socket.accept(); InputStream instr = sc.getInputStream(); DataInputStream dataInputStream = new DataInputStream(instr); System.out.println(dataInputStream.readUTF()); } } catch (IOException e) { e.printStackTrace(); } } } Client import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class TCPClient { public static void main(String[] args) { try { Socket socket = new Socket("127.0.0.1",4444); OutputStream oStream = socket.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(oStream); dataOutputStream.writeUTF("Hello"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } UDP: Server: import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UDPServer { public static void main(String[] args) { try { byte [] buffer = new byte[1024]; DatagramSocket socket = new DatagramSocket(4444); DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while(true){ socket.receive(packet); System.out.println(new String(buffer,0,packet.getLength())); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } Client import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; public class UDPClient { public static void main(String[] args) { byte [] buffer = null; buffer = new String("hello").getBytes(); DatagramPacket packet=null; try { packet = new DatagramPacket(buffer, buffer.length,new InetSocketAddress("127.0.0.1", 4444)); DatagramSocket socket = new DatagramSocket(1234); socket.send(packet); socket.close(); } catch (SocketException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
java网络五子棋 下面的源代码分为4个文件; chessClient.java:客户端主程序。 chessInterface.java:客户端的界面。 chessPad.java:棋盘的绘制。 chessServer.java:服务器端。 可同时容纳50个人同时在线下棋,聊天。 没有加上详细注释,不过绝对可以运行,j2sdk1.4下通过。 /********************************************************************************************* 1.chessClient.java **********************************************************************************************/ import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; class clientThread extends Thread { chessClient chessclient; clientThread(chessClient chessclient) { this.chessclient=chessclient; } public void acceptMessage(String recMessage) { if(recMessage.startsWith("/userlist ")) { StringTokenizer userToken=new StringTokenizer(recMessage," "); int userNumber=0; chessclient.userpad.userList.removeAll(); chessclient.inputpad.userChoice.removeAll(); chessclient.inputpad.userChoice.addItem("所有人"); while(userToken.hasMoreTokens()) { String user=(String)userToken.nextToken(" "); if(userNumber>0 && !user.startsWith("[inchess]")) { chessclient.userpad.userList.add(user); chessclient.inputpad.userChoice.addItem(user); } userNumber++; } chessclient.inputpad.userChoice.select("所有人"); } else if(recMessage.startsWith("/yourname ")) { chessclient.chessClientName=recMessage.substring(10); chessclient.setTitle("Java五子棋客户端 "+"用户名:"+chessclient.chessClientName); } else if(recMessage.equals("/reject")) { try { chessclient.chesspad.statusText.setText("不能加入游戏"); chessclient.controlpad.cancelGameButton.setEnabled(false); chessclient.controlpad.joinGameButton.setEnabled(true); chessclient.controlpad.creatGameButton.setEnabled(true); } catch(Exception ef) { chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭"); } chessclient.controlpad.joinGameButton.setEnabled(true); } else if(recMessage.startsWith("/peer ")) { chessclient.chesspad.chessPeerName=recMessage.substring(6); if(chessclient.isServer) { chessclient.chesspad.chessColor=1; chessclient.chesspad.isMouseEnabled=true; chessclient.chesspad.statusText.setText("请黑棋下子"); } else if(chessclient.isClient) { chessclient.chesspad.chessColor=-1; chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子..."); } } else if(recMessage.equals("/youwin")) { chessclient.isOnChess=false; chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor); chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接"); chessclient.chesspad.isMouseEnabled=false; } else if(recMessage.equals("/OK")) { ……………………………………………………………………………………catch(Exception ee) { } } System.exit(0); } public void windowActivated(WindowEvent ea) { } }); add(westPanel,BorderLayout.WEST); add(centerPanel,BorderLayout.CENTER); add(southPanel,BorderLayout.SOUTH); pack(); setSize(670,548); setVisible(true); setResizable(false); validate(); } public boolean connectServer(String serverIP,int serverPort) throws Exception { try { chatSocket=new Socket(serverIP,serverPort); in=new DataInputStream(chatSocket.getInputStream()); out=new DataOutputStream(chatSocket.getOutputStream()); clientThread clientthread=new clientThread(this); clientthread.start(); isOnChat=true; return true; } catch(IOException ex) { chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序 \n"); } return false; } public void actionPerformed(ActionEvent e) { if(e.getSource()==controlpad.connectButton) { host=chesspad.host=controlpad.inputIP.getText(); try { if(connectServer(host,port)) { chatpad.chatLineArea.setText(""); controlpad.connectButton.setEnabled(false); controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); chesspad.statusText.setText("连接成功,请创建游戏或加入游戏"); } } catch(Exception ei) { chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序 \n"); } } if(e.getSource()==controlpad.exitGameButton) { if(isOnChat) { try { chatSocket.close(); } catch(Exception ed) { } } if(isOnChess || isGameConnected) { try { chesspad.chessSocket.close(); } catch(Exception ee) { } } System.exit(0); } if(e.getSource()==controlpad.joinGameButton) { String selectedUser=userpad.userList.getSelectedItem(); if(selectedUser==null || selectedUser.startsWith("[inchess]") || selectedUser.equals(chessClientName)) { chesspad.statusText.setText("必须先选定一个有效用户"); } else { try { if(!isGameConnected) { if(chesspad.connectServer(chesspad.host,chesspad.port)) { isGameConnected=true; isOnChess=true; isClient=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName); } } else { isOnChess=true; isClient=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName); } } catch(Exception ee) { isGameConnected=false; isOnChess=false; isClient=false; controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ee); } } } if(e.getSource()==controlpad.creatGameButton) { try { if(!isGameConnected) { if(chesspad.connectServer(chesspad.host,chesspad.port)) { isGameConnected=true; isOnChess=true; isServer=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName); } } else { isOnChess=true; isServer=true; controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(true); chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName); } } catch(Exception ec) { isGameConnected=false; isOnChess=false; isServer=false; controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); ec.printStackTrace(); chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ec); } } if(e.getSource()==controlpad.cancelGameButton) { if(isOnChess) { chesspad.chessthread.sendMessage("/giveup "+chessClientName); chesspad.chessVictory(-1*chesspad.chessColor); controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); chesspad.statusText.setText("请建立游戏或者加入游戏"); } if(!isOnChess) { controlpad.creatGameButton.setEnabled(true); controlpad.joinGameButton.setEnabled(true); controlpad.cancelGameButton.setEnabled(false); chesspad.statusText.setText("请建立游戏或者加入游戏"); } isClient=isServer=false; } } public void keyPressed(KeyEvent e) { TextField inputWords=(TextField)e.getSource(); if(e.getKeyCode()==KeyEvent.VK_ENTER) { if(inputpad.userChoice.getSelectedItem().equals("所有人")) { try { out.writeUTF(inputWords.getText()); inputWords.setText(""); } catch(Exception ea) { chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n"); userpad.userList.removeAll(); inputpad.userChoice.removeAll(); inputWords.setText(""); controlpad.connectButton.setEnabled(true); } } else { try { out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText()); inputWords.setText(""); } catch(Exception ea) { chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n"); userpad.userList.removeAll(); inputpad.userChoice.removeAll(); inputWords.setText(""); controlpad.connectButton.setEnabled(true); } } } } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public static void main(String args[]) { chessClient chessClient=new chessClient(); } } /****************************************************************************************** 下面是:chessInteface.java ******************************************************************************************/ import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; class userPad extends Panel { List userList=new List(10); userPad() { setLayout(new BorderLayout()); for(int i=0;i<50;i++) { userList.add(i+"."+"没有用户"); } add(userList,BorderLayout.CENTER); } } class chatPad extends Panel { TextArea chatLineArea=new TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY); chatPad() { setLayout(new BorderLayout()); add(chatLineArea,BorderLayout.CENTER); } } class controlPad extends Panel { Label IPlabel=new Label("IP",Label.LEFT); TextField inputIP=new TextField("localhost",10); Button connectButton=new Button("连接主机"); Button creatGameButton=new Button("建立游戏"); Button joinGameButton=new Button("加入游戏"); Button cancelGameButton=new Button("放弃游戏"); Button exitGameButton=new Button("关闭程序"); controlPad() { setLayout(new FlowLayout(FlowLayout.LEFT)); setBackground(Color.pink); add(IPlabel); add(inputIP); add(connectButton); add(creatGameButton); add(joinGameButton); add(cancelGameButton); add(exitGameButton); } } class inputPad extends Panel { TextField inputWords=new TextField("",40); Choice userChoice=new Choice(); inputPad() { setLayout(new FlowLayout(FlowLayout.LEFT)); for(int i=0;i<50;i++) { userChoice.addItem(i+"."+"没有用户"); } userChoice.setSize(60,24); add(userChoice); add(inputWords); } } /********************************************************************************************** 下面是:chessPad.java **********************************************************************************************/ import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; class chessThread extends Thread { chessPad chesspad; chessThread(chessPad chesspad) { this.chesspad=chesspad; } public void sendMessage(String sndMessage) { try { chesspad.outData.writeUTF(sndMessage); } catch(Exception ea) { System.out.println("chessThread.sendMessage:"+ea); } } public void acceptMessage(String recMessage) { if(recMessage.startsWith("/chess ")) { StringTokenizer userToken=new StringTokenizer(recMessage," "); String chessToken; String[] chessOpt={"-1","-1","0"}; int chessOptNum=0; while(userToken.hasMoreTokens()) { chessToken=(String)userToken.nextToken(" "); if(chessOptNum>=1 && chessOptNum<=3) { chessOpt[chessOptNum-1]=chessToken; } chessOptNum++; } chesspad.netChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(chessOpt[1]),Integer.parseInt(chessOpt[2])); } else if(recMessage.startsWith("/yourname ")) { chesspad.chessSelfName=recMessage.substring(10); } else if(recMessage.equals("/error")) { chesspad.statusText.setText("错误:没有这个用户,请退出程序,重新加入"); } else { //System.out.println(recMessage); } } public void run() { String message=""; try { while(true) { message=chesspad.inData.readUTF(); acceptMessage(message); } } catch(IOException es) { } } } class chessPad extends Panel implements MouseListener,ActionListener { int chessPoint_x=-1,chessPoint_y=-1,chessColor=1; int chessBlack_x[]=new int[200]; int chessBlack_y[]=new int[200]; int chessWhite_x[]=new int[200]; int chessWhite_y[]=new int[200]; int chessBlackCount=0,chessWhiteCount=0; int chessBlackWin=0,chessWhiteWin=0; boolean isMouseEnabled=false,isWin=false,isInGame=false; TextField statusText=new TextField("请先连接服务器"); Socket chessSocket; DataInputStream inData; DataOutputStream outData; String chessSelfName=null; String chessPeerName=null; String host=null; int port=4331; chessThread chessthread=new chessThread(this); chessPad() { setSize(440,440); setLayout(null); setBackground(Color.pink); addMouseListener(this); add(statusText); statusText.setBounds(40,5,360,24); statusText.setEditable(false); } public boolean connectServer(String ServerIP,int ServerPort) throws Exception { try { chessSocket=new Socket(ServerIP,ServerPort); inData=new DataInputStream(chessSocket.getInputStream()); outData=new DataOutputStream(chessSocket.getOutputStream()); chessthread.start(); return true; } catch(IOException ex) { statusText.setText("chessPad:connectServer:无法连接 \n"); } return false; } public void chessVictory(int chessColorWin) { this.removeAll(); for(int i=0;i<=chessBlackCount;i++) { chessBlack_x[i]=0; chessBlack_y[i]=0; } for(int i=0;i<=chessWhiteCount;i++) { chessWhite_x[i]=0; chessWhite_y[i]=0; } chessBlackCount=0; chessWhiteCount=0; add(statusText); statusText.setBounds(40,5,360,24); if(chessColorWin==1) { chessBlackWin++; statusText.setText("黑棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待白棋下子..."); } else if(chessColorWin==-1) { chessWhiteWin++; statusText.setText("白棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待黑棋下子..."); } } public void getLocation(int a,int b,int color) { if(color==1) { chessBlack_x[chessBlackCount]=a*20; chessBlack_y[chessBlackCount]=b*20; chessBlackCount++; } else if(color==-1) { chessWhite_x[chessWhiteCount]=a*20; chessWhite_y[chessWhiteCount]=b*20; chessWhiteCount++; } } public boolean checkWin(int a,int b,int checkColor) { int step=1,chessLink=1,chessLinkTest=1,chessCompare=0; if(checkColor==1) { chessLink=1; for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if(((a+step)*20==chessBlack_x[chessCompare]) && ((b*20)==chessBlack_y[chessCompare])) { chessLink=chessLink+1; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if(((a-step)*20==chessBlack_x[chessCompare]) && (b*20==chessBlack_y[chessCompare])) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } chessLink=1; chessLinkTest=1; for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if((a*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare])) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if((a*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare])) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } chessLink=1; chessLinkTest=1; for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if(((a-step)*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare])) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if(((a+step)*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare])) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } chessLink=1; chessLinkTest=1; for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if(((a+step)*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare])) { chessLink++; if(chessLink==5) { return(true); } } } if(chessLink==(chessLinkTest+1)) chessLinkTest++; else break; } for(step=1;step<=4;step++) { for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++) { if(((a-step)*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare])) { chessLink++; if(chessLink==5) { return(true); } }
import java.io.*; import java.net.*; import java.util.*; public class Server { public static void main(String args[]){ try { ServerSocket server = new ServerSocket(8888); System.out.println("服务器在监听8888端口..."); while (true) { Socket socket = server.accept(); new ReceFile(socket).start(); } } catch (Exception e) { e.printStackTrace(); } } } //服务器接收文件线程 class ReceFile extends Thread { private Socket socket; public ReceFile(Socket socket){ this.socket = socket; } public void run(){ InputStream is = null; OutputStream os = null; DataInputStream dis = null; InetAddress address = null; String ip = ""; try { //获得输入流 is = socket.getInputStream(); //获取连接此输入流的地址 address = socket.getInetAddress(); //返回ip ip = address.getHostAddress(); dis = new DataInputStream(is); //读取上传过过来的文件名 String fileName = dis.readUTF(); System.out.println("服务器接收到自"+ip+"的"+fileName+"文件"); //将接收到的文件保存到指定的目录 os = new FileOutputStream("File/"+fileName); int len = 0; byte[] b = new byte[1024]; while (true) { len = is.read(b); if (len==-1) { break; } os.write(b,0,len); os.flush(); } } catch (Exception e) { e.printStackTrace(); } finally{ try { if (is!=null) { is.close(); } if (dis!=null) { dis.close(); } if (os!=null) { os.close(); } } catch (Exception ex) { ex.printStackTrace(); } } } } import java.io.*; import java.net.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import org.roy.*; public class Client extends JFrame implements ActionListener { private JButton selbutton,upbutton; private JPanel jp; private String path; public Client(){ super("文件上传"); this.setSize(250,250); this.setLocation(300,400); init(); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } public void init(){ selbutton = new JButton("选择文件"); upbutton = new JButton("上 传"); jp = new JPanel(); selbutton.addActionListener(this); upbutton.addActionListener(this); jp.add(selbutton); jp.add(upbutton); this.add(jp); } public void actionPerformed(ActionEvent e){ if(e.getSource()==selbutt

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值