java Socket编程 客户端与服务器端在两个网里怎么实现连接 s = new Socket("127.0.0.1", 8880);这个IP怎么
s
=
new
socket("127001",
8880)
前面那个ip是服务器的地址,只要这个ip写正确了,服务器放在哪里,客户端都能连上去的。
1270。01最简单的解释就是本机地址,你用这个ip,访问的就是你自己。
你可以去服务器上查看一下网络地址,然后把1270。01换成服务器的ip。
写个简单点的服务器跟客服端就行了我写了个很简单的,只能在一个客户端跟一个服务器通信,在控制台输入下面这个是服务器import javaio;
import javanet;
import javautilScanner;public class Server
{
public static void main(String[] args)
{
try {
ServerSocket server=new ServerSocket(8888);//定义客户端的端口号
Socket client=serveraccept();//定义一个Socket对象
InputStream is=clientgetInputStream();//服务器接受信息输入流,也就是接受从服务器段发送过来的消息
BufferedReader br=new BufferedReader(new InputStreamReader(is));//用bufferedreader包装下输入流
OutputStream os=clientgetOutputStream();//这是用来给服务器发送消息的输出流
PrintStream ps=new PrintStream(os);
Scanner scanner=new Scanner(Systemin);//从键盘输入字符串
boolean flag=true;//定义一个死循环,让服务器不停的接受从客户端发送来的字符串
while(flag)
{
String s=brreadLine();//s是从客户端接受到得字符串
Systemoutprintln(s);
String s2=scannernextLine();//s2是写给客户端的字符串
psprintln(s2); //给客户端发送你写的东西
}
clientclose();
} catch (IOException e) {//try 跟catch你不用管,这是用来处理异常的,就是固定格式
eprintStackTrace();
}
}
} 下面是客户端import javaio;
import javanet;
import javautilScanner;public class Client
{ public static void main(String[] args)
{
try
{
Socket client=new Socket("192168----",8888);//IP地址是个字符串,端口号是个整数,这个端口号要跟前面你写的那个一样,还有IP地址,写你的机器的IP地址
InputStream is=clientgetInputStream();//这边的两个流跟上面服务器的差不多的作用
BufferedReader bf=new BufferedReader(new InputStreamReader(is));
OutputStream os=clientgetOutputStream();
PrintStream ps=new PrintStream(os);
Scanner scanner=new Scanner(Systemin);
boolean flag=true;
while(flag)//这句话可以让客户端不停的说话
{
String s2=scannernextLine();
psprintln(s2);
String s=bfreadLine();
Systemoutprintln(s); }
clientclose();
}
catch (UnknownHostException e)
{
eprintStackTrace();
}
catch (IOException e)
{
eprintStackTrace();
} }}
使用session机制,将参数动态的放在url后或使用cookies保存,将信息保存在url后或url链接后面。从服务器上再保存一份,就可以了。不过实现起来太复杂了。 暂不做介绍
现在有一个简单的办法就是可以在发送的消息前面加入一个随机值,当有新的请求到来的时候创建一个,然后保存起来。当客户端接收到这个随机值的时候,再回信息的时候将这个消息一并发给服务器。服务器可以这样判断,如果没有这个消息值的话就认为是一个新的用户,并为其创建一个消息。如果带有这消息的话,就是已经链接过的。这样就可以保持链接状态了。
import javaio;
import javanet;
import javautil;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();//创建一个线程数组,这样每连接一个客户端就开启一个线程管理
public static void main(String[] args) {
new ChatServer()start();
}
public void start() {
try {
ss = new ServerSocket(8888);//服务器端监听8888号端口,如果有客户端向这个端口发起请求就可以被服务器端监听到
started = true;
} catch (BindException e) {
Systemoutprintln("端口使用中");
Systemoutprintln("请关掉相关程序并重新运行服务器!");
Systemexit(0);
} catch (IOException e) {
eprintStackTrace();
}
try {
while(started) {
Socket s = ssaccept();//服务器等待客户端的连接
Client c = new Client(s);//如果有客户端发出请求,把s传给Client
Systemoutprintln("a client connected!");
new Thread(c)start();//启动一个新进程,客户端与服务端建立通信
clientsadd(c);//
}
} catch (IOException e) {
eprintStackTrace();
} finally {
try {
ssclose();
} catch (IOException e) {
eprintStackTrace();
}
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
thiss = s;
try {
dis = new DataInputStream(sgetInputStream());//建立通信后,获得输入流
dos = new DataOutputStream(sgetOutputStream());//获得输出流
bConnected = true;
} catch (IOException e) {
eprintStackTrace();
}
}
public void send(String str) {
try {
doswriteUTF(str);//向流里面写入数据str
} catch (IOException e) {
eprintStackTrace();
}
}
public void run() {
try {
while(bConnected) {
String str = disreadUTF();//从流里面读取数据赋给str
Systemoutprintln(str);
for(int i=0; i<new ChatServer()clientssize(); i++) {
Client c = new ChatServer()clientsget(i);
csend(str);
}
}
} catch (EOFException e) {
Systemoutprintln("Client closed!");
} catch (IOException e) {
eprintStackTrace();
} finally {
try {
if(dis != null) disclose();
if(dos != null) dosclose();
if(s != null) {
sclose();
//s = null;
}
} catch (IOException e1) {
e1printStackTrace();
}
}
}
}
主要就是这些,客户端的程序不完整,而且跟服务端差不多,你对照着书看 应该能看懂
程序分Server和Client
服务器端打开侦听的端口,一有客户端连接就创建两个新的线程来负责这个连接
一个负责客户端发送的信息(ClientMsgCollectThread 类),
另一个负责通过该Socket发送数据(ServerMsgSendThread )
Serverjava代码如下:
/
创建日期 2009-3-7
TODO 要更改此生成的文件的模板,请转至
窗口 - 首选项 - Java - 代码样式 - 代码模板
/
package faueMutiUser;
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetServerSocket;
import javanetSocket;
/
服务器端
@author Faue
/
public class Server extends ServerSocket {
private static final int SERVER_PORT = 10000;
/
构造方法,用于实现连接的监听
@throws IOException
/
public Server() throws IOException {
super(SERVER_PORT);
try {
while (true) {
Socket socket = superaccept();
new Thread(new ClientMsgCollectThread(socket), "getAndShow"
+ socketgetPort())start();
new Thread(new ServerMsgSendThread(socket), "send"
+ socketgetPort())start();
}
} catch (IOException e) {
eprintStackTrace();
}
}
public static void main(String[] args) throws IOException {
new Server();
}
/
该类用于创建接收客户端发来的信息并显示的线程
@author Faue
@version 100
/
class ClientMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/
得到Socket的输入流
@param s
@throws IOException
/
public ClientMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
getInputStream(), "GBK"));
}
public void run() {
try {
while (!clientisClosed()) {
inputStringBufferdelete(0, inputStringBufferlength());
inputStringBufferappend(inreadLine());
Systemoutprintln(getMsg(inputStringBuffertoString()));
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
}
}
/
构造显示的字符串
@param line
@return
/
private String getMsg(String line) {
return clienttoString() + " says:" + line;
}
}
/
该类用于创建发送数据的线程
@author Faue
@version 100
/
class ServerMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/
得到键盘的输入流
@param s
@throws IOException
/
public ServerMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(clientgetOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(Systemin));
}
public void run() {
try {
while (!clientisClosed()) {
outputStringBufferdelete(0, outputStringBufferlength());
outputStringBufferappend(keyboardInputreadLine());
outprintln(outputStringBuffertoString());
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
}
}
}
}
客户端:
实现基于IP地址的连接,连接后也创建两个线程来实现信息的发送和接收
/
创建日期 2009-3-7
/
package faueMutiUser;
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetSocket;
/
客户端
@author Faue
/
public class Client {
private Socket mySocket;
/
创建线程的构造方法
@param IP
@throws IOException
/
public Client(String IP) throws IOException {
try {
mySocket = new Socket(IP, 10000);
new Thread(new ServerMsgCollectThread(mySocket), "getAndShow"
+ mySocketgetPort())start();
new Thread(new ClientMsgSendThread(mySocket), "send"
+ mySocketgetPort())start();
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln("ServerIP:" + IP
+ " port:10000 can not be Connected");
}
}
public static void main(String[] args) throws IOException {
try {
new Client(args[0]);
} catch (Exception e) {
Systemoutprintln("输入的IP地址错误");
}
}
/
该类用于创建接收服务端发来的信息并显示的线程
@author Faue
@version 100
/
class ServerMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/
得到Socket的输入流
@param s
@throws IOException
/
public ServerMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
getInputStream(), "GBK"));
}
public void run() {
try {
while (!clientisClosed()) {
inputStringBufferdelete(0, inputStringBufferlength());
inputStringBufferappend(inreadLine());
Systemoutprintln(getMsg(inputStringBuffertoString()));
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
Systemexit(0);
}
}
/
构造输入字符串
@param line
@return
/
private String getMsg(String line) {
return clienttoString() + " says:" + line;
}
}
/
该类用于创建发送数据的线程
@author Faue
@version 100
/
class ClientMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/
得到键盘的输入流
@param s
@throws IOException
/
public ClientMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(clientgetOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(Systemin));
}
public void run() {
try {
while (!clientisClosed()) {
outputStringBufferdelete(0, outputStringBufferlength());
outputStringBufferappend(keyboardInputreadLine());
outprintln(outputStringBuffertoString());
}
outprintln("--- See you, bye! ---");
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
Systemexit(0);
}
}
}
}
如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!
vaela
PrintWriter out = new PrintWriter(sgetOutputStream());
outwrite("你好!");
替换成
PrintStream out = new PrintStream(sgetOutputStream());
outprint("你好!");
网站模板库 » java Socket编程 客户端与服务器端在两个网里怎么实现连接 s = new Socket("127.0.0.1", 8880);这个IP怎么
0条评论