新手请教JAVA,SOCKET网络编程

hz03zhuhaowen 2010-02-06 04:40:14

package com.cn.socket;

import java.io.*;
import java.net.*;

public class TcpServer {
// 服务器端源程序tcpserver.Java
/**
* @param args
*/
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
ServerSocket svrsoc=null;
Socket soc=null;
DataInputStream in=null;
PrintStream out=null;
InetAddress clientIP=null;
String str=null;
try{
svrsoc=new ServerSocket(8000);
System.out.println("Server start....");
soc=svrsoc.accept();

in=new DataInputStream(soc.getInputStream());
out=new PrintStream(soc.getOutputStream());
clientIP=soc.getInetAddress();
System.out.println("Client's IP address:"+clientIP);
out.println("welcome.....");
str=in.readLine();
while (!str.equals("quit")){
System.out.println("Client said:"+str);
str=in.readLine();
}
System.out.println("Client want to leave");
}
catch(Exception e){
System.out.println("error:"+e);
}
finally{
in.close();
out.close();
soc.close();
svrsoc.close();
System.exit(0);
}
}

}

以上是服务端代码

package com.cn.socket;

import java.io.*;
import java.net.*;

public class TcpClient {
// 客户端源程序tcpclient.java
/**
* @param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Socket soc=null;
DataInputStream in=null;
PrintStream out=null;
DataInputStream sysin=null;
String strin=null;
String strout=null;
try{
soc=new Socket(args[0],8000);
System.out.println("Connecting to the Server");
in=new DataInputStream(soc.getInputStream());
out=new PrintStream(soc.getOutputStream());
strin=in.readLine();
System.out.println("Server said:"+strin);
sysin=new DataInputStream(System.in);
strout=sysin.readLine();
while (!strout.equals("quit")){
out.println(strout);
strout=sysin.readLine();
}
out.println(strout);
}
catch(Exception e){
System.out.println("error:"+e);
}
finally{
in.close();
out.close();
soc.close();
sysin.close();
System.exit(0);
}
}

}

以上是客户端代码,我把服务端,客户端的代码都放到一个包里,
然后我在本机上运行它们,我先运行服务端,有运行程序,然后
运行客户端代码,并且给了相应的IP地址(我是用Eclipse工具),结果客户端,
服务端都报错,错误如下:
error:java.net.BindException: Address already in use: JVM_Bind
Exception in thread "main" java.lang.NullPointerException
at com.cn.socket.TcpServer.main(TcpServer.java:40)
请问我该怎么运行这个程序。
...全文
135 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
teemai 2010-02-06
  • 打赏
  • 举报
回复
换个别的端口再试试吧
humanity 2010-02-06
  • 打赏
  • 举报
回复
它说端口正在使用,你用 serverSocket.setReuseAddress(true) 看行不行。

58,454

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧