关于线程和socket通信。
实现客户端和服务端互发消息。比较简陋
客户端代码:
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
clent();
}
public static void clent() throws IOException {
System.out.println("正在发送请求...");
Socket client = null;
Scanner keybordscanner = null; //获取键盘输入
PrintWriter pwoWriter=null; //用来发送消息给客户端。
String host = "127.0.0.1";
int port =9999;
client = new Socket(host, port);
Recv recv = new Recv(client);
System.out.println(client.getInetAddress().toString()+"建立连接");
new Thread(recv).start();
pwoWriter=new PrintWriter(client.getOutputStream());
keybordscanner =new Scanner(System.in);
int flag=1;
while (flag==1){
System.out.print("客户端:");
String keybarddata = keybordscanner.nextLine();
if(keybarddata.equals("quit"))
flag=0;
pwoWriter.println(keybarddata);
pwoWriter.flush(); //清空发送的缓冲区
}
//关闭输入输出流和socket连接
pwoWriter.close();
keybordscanner.close();
client.close();
}
}
服务端代码:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
// write your code here
Sever sever=new Sever();
sever.Severs();
}
public static void Sever2() throws IOException {
ServerSocket sever2=new ServerSocket(8888);
Socket client =sever2.accept();
}
}
class Sever{
public void Severs() throws IOException {
int port=9999;
PrintWriter pwtoclien = null; //用来发送消息给客户端。
Scanner keybordscanner=null; //获取键盘输入
InetAddress address=InetAddress.getByName("127.0.0.1");
ServerSocket sever=new ServerSocket(port,20,address);
//接收连接
Socket client =sever.accept();
//开启新线程接收消息
Recv recv = new Recv(client);
System.out.println(client.getInetAddress().toString()+"建立连接");
new Thread(recv).start(); //创建一个线程,接受消息,并打印出来
pwtoclien= new PrintWriter(client.getOutputStream());
keybordscanner= new Scanner(System.in);
while(client.isClosed()==false){
System.out.print("服务端:");
String keydata = keybordscanner.nextLine();
pwtoclien.println(keydata);
pwtoclien.flush();
}
System.out.println("客户端连接已关闭。");
client.close();
sever.close();
}
}
以下代码用来接收消息
Recv.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Recv implements Runnable{
Socket socket;
Scanner inscanner;
PrintWriter printWriter;
Recv(Socket socket){
this.socket=socket;
}
@Override
public void run() {
try {
inscanner = new Scanner(socket.getInputStream());
printWriter=new PrintWriter(socket.getOutputStream());
while( inscanner.hasNextLine()&&socket.isConnected()){
String data = inscanner.nextLine();
if(!data.equals("get it!")) {
System.out.println(data);
printWriter.println("get it!");
printWriter.flush();
}
}
System.out.println("断开连接");
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inscanner!=null){
inscanner.close();
}
if(printWriter!=null)
printWriter.close();
}
}
}