新手请教JAVA,SOCKET网络编程

hz03zhuhaowen hz03zhuhaowen 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

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)
请问我该怎么运行这个程序。
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
hz03zhuhaowen
Eclipse 58,439 成员 49,457 内容